将2-d列表转换为数据帧

时间:2014-08-08 22:29:49

标签: r list

除了代表列表编号的额外变量name之外,我如何将下面的列表o转换为长jy的长数据帧,即o [,y这里的y是1或2。

> dput(o)
structure(list(c("Mary", "John", "Michael", "Robert", "Jennifer", 
"Jacob", "James", "Emily", "Jessica", "Lisa", "Linda", "Sophia", 
"Ashley", "Isabella", "David", "Emma", "Noah"), c(0.567164179104478, 
0.328358208955224, 0.328358208955224, 0.126865671641791, 0.111940298507463, 
0.104477611940299, 0.0970149253731343, 0.0895522388059701, 0.0671641791044776, 
0.0597014925373134, 0.0447761194029851, 0.0223880597014925, 0.0149253731343284, 
0.0149253731343284, 0.00746268656716418, 0.00746268656716418, 
0.00746268656716418), c("Mary", "Michael", "John", "William", 
"Robert", "James", "Anna", "Helen", "Christopher", "Jessica", 
"Jacob", "Jennifer", "Emily", "Ashley", "David", "Linda", "Lisa", 
"Barbara", "Dorothy", "Emma", "Betty", "Isabella", "Jason", "Amy", 
"Michelle", "Sophia", "Susan", "Hannah", "Melissa", "Ethan", 
"Kimberly", "Madison", "Mason", "Matthew", "Shirley", "Amanda", 
"Deborah", "Debra", "Liam", "Noah"), c(0.641791044776119, 0.41044776119403, 
0.388059701492537, 0.298507462686567, 0.246268656716418, 0.23134328358209, 
0.149253731343284, 0.149253731343284, 0.134328358208955, 0.126865671641791, 
0.119402985074627, 0.111940298507463, 0.0895522388059701, 0.082089552238806, 
0.0746268656716418, 0.0746268656716418, 0.0746268656716418, 0.0597014925373134, 
0.0597014925373134, 0.0597014925373134, 0.0522388059701493, 0.0373134328358209, 
0.0373134328358209, 0.0298507462686567, 0.0298507462686567, 0.0298507462686567, 
0.0298507462686567, 0.0223880597014925, 0.0223880597014925, 0.0149253731343284, 
0.0149253731343284, 0.0149253731343284, 0.0149253731343284, 0.0149253731343284, 
0.0149253731343284, 0.00746268656716418, 0.00746268656716418, 
0.00746268656716418, 0.00746268656716418, 0.00746268656716418
)), .Dim = c(2L, 2L), .Dimnames = list(c("name", "j"), NULL))

2 个答案:

答案 0 :(得分:3)

## Make a list of data.frames, one from each column of your input matrix
ll <- lapply(seq_len(ncol(o)), FUN = function(i) data.frame(id=i, o[,i]))

## Then rbind them all together into a single data.frame
df <- do.call(rbind, ll)

## Finally, check that it worked
df[c(1:2, 56:57),]
#    id    name           j
# 1   1    Mary 0.567164179
# 2   1    John 0.328358209
# 56  2    Liam 0.007462687
# 57  2    Noah 0.007462687
str(df)
# 'data.frame':   57 obs. of  3 variables:
#  $ id  : int  1 1 1 1 1 1 1 1 1 1 ...
#  $ name: Factor w/ 40 levels "Ashley","David",..: 13 10 14 16 8 6 7 3 9 12 ...
#  $ j   : num  0.567 0.328 0.328 0.127 0.112 ...

答案 1 :(得分:1)

或者你可以这样做:

 library(reshape2)
 res <-setNames(cbind(melt(o[c(T,F)]), melt(o[c(F,T)])[,1])[,c(2,1,3)], c("id", "name", "j"))

   res[c(1:2, 56:57),]
   # id name           j
 #1   1 Mary 0.567164179
 #2   1 John 0.328358209
 #56  2 Liam 0.007462687
 #57  2 Noah 0.007462687