Anna1364 Anna1364 - 3 years ago 152
R Question

how to add add list element names as a variable in the output

I have a list of data.frames looks like this:

$IB1Q
V1 V2 V3 V4 V5 V6 V7 V8
0.184011746 0.805070251 0.840738769 0.701748191 0.493042421 0.889981450 0.003934755 0.794561335
V9 V10 V11
0.664718057 0.880357401 0.545795252

$IBCA
V1 V2 V3 V4 V5 V6 V7 V8 V9
0.8719393 0.8177656 0.9205127 0.7200678 0.7456413 0.4643883 0.8006192 0.1430972 0.7622733
V10 V11
0.4716331 0.8681162


and each element name (IB1Q, IBCA) conveys information. I want to row.bind them together and in my data.farme I want a
variable for the list elemnt each observation originated in.
So I want to get a data.frame with 2 columns (first column popID and second columns my proportions):

IB1Q 0.184011746
IB1Q 0.805070251
IB1Q 0.840738769
IB1Q 0.701748191
IB1Q 0.493042421
.
.
.
IBCA 0.4716331
IBCA 0.8681162

Answer Source

Here's one thought:

mylist <- list(
  IB1Q = as.data.frame(setNames(
    list(0.184011746, 0.805070251, 0.840738769, 0.701748191, 0.493042421, 0.889981450, 0.003934755, 0.794561335, 0.664718057, 0.880357401, 0.545795252),
    paste0("V", 1:11)
  )),
  IBCA = as.data.frame(setNames(
    list(0.8719393, 0.8177656, 0.9205127, 0.7200678, 0.7456413, 0.4643883, 0.8006192, 0.1430972, 0.7622733, 0.4716331, 0.8681162),
    paste0("V", 1:11)
  ))
)

do.call(rbind.data.frame,
        lapply(names(mylist), function(n) data.frame(K=n, V=unlist(mylist[[n]], use.names = FALSE)))
        )
#       K           V
# 1  IB1Q 0.184011746
# 2  IB1Q 0.805070251
# 3  IB1Q 0.840738769
# 4  IB1Q 0.701748191
# 5  IB1Q 0.493042421
# 6  IB1Q 0.889981450
# 7  IB1Q 0.003934755
# 8  IB1Q 0.794561335
# 9  IB1Q 0.664718057
# 10 IB1Q 0.880357401
# 11 IB1Q 0.545795252
# 12 IBCA 0.871939300
# 13 IBCA 0.817765600
# 14 IBCA 0.920512700
# 15 IBCA 0.720067800
# 16 IBCA 0.745641300
# 17 IBCA 0.464388300
# 18 IBCA 0.800619200
# 19 IBCA 0.143097200
# 20 IBCA 0.762273300
# 21 IBCA 0.471633100
# 22 IBCA 0.868116200

Since we're discarding the column names of the nested data.frames, I don't think the use of unlist is too harsh/lossy. (I use use.names=FALSE because I find row names to be unreliable in the long run ... feel free to keep them if you'd like.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download