我有多个如下所示的列表:我在将这些列表转换为R中的数据帧时遇到问题
我在R中编写了很少的代码以将列表转换为数据框,但是给出了错误的数据框
### the first list
b1
[[1]]
[1] "math"
[[2]]
[1] "write"
[[3]]
[1] 0.6439442
[[4]]
[1] 0.2939780 0.8416635
[[5]]
2.5% 97.5%
0.5517048 0.7156524
## second list
b2
[[1]]
[1] "math"
[[2]]
[1] "read"
[[3]]
[1] 0.663126
[[4]]
[1] 0.3242639 0.8511580
[[5]]
2.5% 97.5%
0.5716105 0.7384209
3 third list
b3
[[1]]
[1] "science"
[[2]]
[1] "write"
[[3]]
[1] 0.5812035
[[4]]
[1] 0.1995946 0.8097306
[[5]]
2.5% 97.5%
0.4791782 0.6721795
为此,我编写了一个代码,将多个列表转换为R中的数据框
已将所有列表合并为一个列表,可以轻松地在数据框中进行转换
list_full <- list(b1,b2,b2,b4)
f1 <- lapply(list_full,function(x){
max.length<-max(sapply(x, length))
data.frame(sapply(x, function(v) {c(v, rep(NA, max.length-length(v)))}), stringsAsFactors = FALSE)
})
library(dplyr)
j<-bind_rows(f1, .id = 'ID')
ID X1 x2 x3 x4 x5
1 1 math write 0.64394 0.2939780 0.55170476
2 1 NA NA NA 0.841663 0.7156523
3 2 math read 0.6631 0.324263 0.57161
4 2 NA NA NA 0.851157 0.7384209
5 3 math read 0.6631 0.3242 0.5716104
6 3 NA NA NA 0.85115 0.7384
7 4 science read 0.644 0.2963 0.552
8 4 NA NA NA 0.842 0.72
x1 x2 x3 x4 x5
math wirte 0.643 (0.29, 0.84) (0.55, 0.72)
math read 0.66 (0.32 0.851) (0.57 0.74)
science write 0.581 (0.19 0.80) (0.47 0.67)
答案 0 :(得分:2)
这是尝试对列表进行 schema: {
cdCovers: {
type: 'string',
title: 'CD Covers',
},
dvdCovers: {
type: 'string',
title: 'DVD Covers',
},
cards: {
type: 'string',
title: 'Cards',
},
posters: {
type: 'string',
title: 'Posters',
},
cups: {
type: 'string',
title: 'Cups',
},
}
};```
ping,然后对结果进行Map
-ing。
paste
来源列表在哪里:
allb <- do.call(Map, c(rbind, list(b1,b2,b3)))
allb <- lapply(allb, function(x) {
if(ncol(x) > 1) paste0("(", apply(x,1,paste,collapse=", "), ")") else
x
})
as.data.frame(allb, col.names = paste0("x", seq_along(allb)))
# x1 x2 x3 x4 x5
#1 math write 0.6439442 (0.293978, 0.8416635) (0.5517048, 0.7156524)
#2 math read 0.6631260 (0.3242639, 0.851158) (0.5716105, 0.7384209)
#3 science write 0.5812035 (0.1995946, 0.8097306) (0.4791782, 0.6721795)