这是我的数据框架
>head(dat)
Var1 Freq
1 89 2
2 95 2
3 97 1
4 99 2
5 103 2
6 104 2我想在for循环上迭代并使用cbind追加dat$freq。当Freq发生在Freq中时,是否可以将NA附加到相同的Freq
发布于 2014-04-16 11:24:45
我认为OP正在寻找merge --一个data.frames列表,而不是cbind
跟随应该能起作用。
DF.LIST <- lapply(1:5, function(x) {
rows <- sample(1:5, 1)
data.frame(Var1 = sample(1:5, rows), Freq = sample(5:10, rows))
})
DF.LIST
## [[1]]
## Var1 Freq
## 1 2 6
## 2 4 7
## 3 3 9
## 4 5 10
##
## [[2]]
## Var1 Freq
## 1 3 10
## 2 2 9
##
## [[3]]
## Var1 Freq
## 1 4 5
## 2 3 6
##
## [[4]]
## Var1 Freq
## 1 1 6
## 2 2 10
## 3 5 7
## 4 3 9
## 5 4 8
##
## [[5]]
## Var1 Freq
## 1 5 10
## 选项1
如果在这样的列表中直接使用Reduce & merge组合体,问题在于它最终将与Var1和Freq列合并。为了避免这种情况,我们首先通过添加一个索引号来重命名每个data.frame中的第二列。在那之后,Reduce和merge组合应该提供OP想要的东西。
for (i in 1:length(DF.LIST)) {
names(DF.LIST[[i]]) <- c("Var1", paste0("Freq", i))
}
Reduce(function(...) merge(..., all = T), DF.LIST)
## Var1 Freq1 Freq2 Freq3 Freq4 Freq5
## 1 1 NA NA NA 6 NA
## 2 2 6 9 NA 10 NA
## 3 3 9 10 6 9 NA
## 4 4 7 NA 5 8 NA
## 5 5 10 NA NA 7 10选项2
您可以尝试直接跟踪原始DF.LIST,但是仍然需要处理结果中的列名。
Reduce(function(...) merge(..., by = "Var1", all = T), DF.LIST)
## Var1 Freq.x Freq.y Freq.x Freq.y Freq
## 1 1 NA 6 NA 9 NA
## 2 2 7 NA NA 8 NA
## 3 3 NA 5 NA 7 7
## 4 4 NA 7 5 5 10
## 5 5 9 9 7 6 NA
Warning messages:
1: In merge.data.frame(..., by = "Var1", all = T) :
column names ‘Freq.x’, ‘Freq.y’ are duplicated in the result
2: In merge.data.frame(..., by = "Var1", all = T) :
column names ‘Freq.x’, ‘Freq.y’ are duplicated in the resulthttps://stackoverflow.com/questions/23107154
复制相似问题