[英]How to combine a list and data.frame in R?
我有一个名为data3
的列表,像这样(来自JSON文件)。
data3 <- list(structure(c(14, 7, 10, 4, 7), .Names = c("0", "3", "2", "14", "7")), structure(c(16, 10, 12, 6, 7), .Names = c("0", "3", "2", "14", "7")), structure(c(77708, 39434, 45489, 30223, 34829 ), .Names = c("0", "3", "2", "14", "7")), structure(c(9828, 6855, 7967, 5638, 6263), .Names = c("0", "3", "2", "14", "7")), structure(c(7626, 5783, 6406, 5074, 5348), .Names = c("0", "3", "2", "14", "7")), structure(c(1012, 404, 546, 251, 300), .Names = c("0", "3", "2", "14", "7")))
并且它有一些缺少的值,例如
data3[4]
[[1]]
0 3 2 14 7
9828 6855 7967 5638 6263
> data3[400]
[[1]]
0 3 2
44 35 38
我有一个名为data1
的data.frame,如下所示:
date d1 d2 d3 d4
3 20150402 4 5693 0 NEW
4 20150402 4 5693 0 UPGRADE(OEM)
5 20150402 4 5693 0 UPGRADE(ONLINE)
...
我需要像把它们结合起来
date d1 d2 d3 d4 0 2 3 7 14
20150402 4 5693 0 NEW 77708 39434 45489 30223 34829
问题在于,并非所有的data3
都具有相同数量的元素。
我已经试过了:
aaa <- NULL
for (i in 1:482){
aaa <- cbind(data1[i, ],data3[[i]])
}
但这没用。 也许还有另一种方法可以做到这一点,但我不知道。
我无法复制您的data1
data.frame,因此我要发布一个示例,该示例使用流行的iris
数据集的前6行:
> data3 <- list(structure(c(14, 7, 10, 4, 7), .Names = c("0", "3", "2", "14", "7")), structure(c(16, 10, 12, 6, 7), .Names = c("0", "3", "2", "14", "7")), structure(c(77708, 39434, 45489, 30223, 34829 ), .Names = c("0", "3", "2", "14", "7")), structure(c(9828, 6855, 7967, 5638, 6263), .Names = c("0", "3", "2", "14", "7")), structure(c(7626, 5783, 6406, 5074, 5348), .Names = c("0", "3", "2", "14", "7")), structure(c(1012, 404, 546, 251, 300), .Names = c("0", "3", "2", "14", "7")))
>
>
> t(as.data.frame(data3)) -> x
> rownames(x) <- NULL
> x
0 3 2 14 7
[1,] 14 7 10 4 7
[2,] 16 10 12 6 7
[3,] 77708 39434 45489 30223 34829
[4,] 9828 6855 7967 5638 6263
[5,] 7626 5783 6406 5074 5348
[6,] 1012 404 546 251 300
> cbind(iris[1:6,],x)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species 0 3 2 14 7
1 5.1 3.5 1.4 0.2 setosa 14 7 10 4 7
2 4.9 3.0 1.4 0.2 setosa 16 10 12 6 7
3 4.7 3.2 1.3 0.2 setosa 77708 39434 45489 30223 34829
4 4.6 3.1 1.5 0.2 setosa 9828 6855 7967 5638 6263
5 5.0 3.6 1.4 0.2 setosa 7626 5783 6406 5074 5348
6 5.4 3.9 1.7 0.4 setosa 1012 404 546 251 300
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.