簡體   English   中英

如何在R中合並列表和data.frame?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM