绑定不同行数的列

Cin*_*ina 3 r dataframe cbind

我想创建一个迭代,它采用一个列表(这是另一个数据帧的列)并将其作为列添加到当前数据帧中。但列的长度不相等。所以,我想生成 NA 作为不匹配的行。

seq_actions=as.data.frame(x = NA)
for(i in 1:20){
  temp_seq=another_df$c1[some conditions]  
  seq_actions=cbind(temp_seq,seq_actions)
}
Run Code Online (Sandbox Code Playgroud)

为了简化,假设我有

df
1  3
3  4
2  2
Run Code Online (Sandbox Code Playgroud)

将 5,6 的列表添加为 df 的新列,所以我想要:

 df
    1  3  5
    3  4  6
    2  2  NA
Run Code Online (Sandbox Code Playgroud)

另一个添加列表是 7 7 7 8,所以我的 df 将是:

df
   1  3  5  7
   3  4  6  7
   2  2  NA 7
   NA NA NA 8
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

gri*_*mer 7

这是一种方法。每当您组合数据帧并且未找到匹配项时,合并函数按设计将添加 NA 值(例如,如果 1 个数据帧中的值少于另一个数据帧中的值)。

如果您假设您根据行号来匹配数据框(哪些行放在一起),则只需将行号输出为数据框中的一列即可。然后合并该列。合并将自动添加您想要的 NA 值,并处理数据框具有不同行数的事实。

#test data frame 1
a <- c(1, 3, 2)
b <- c(3, 4, 2)
dat <- as.data.frame(cbind(a, b))

#test data frame 2 (this one has fewer rows than the first data frame)
c <- c(5, 6)
dat.new <- as.data.frame(c)

#add column to each data frame with row number
dat$number <- row.names(dat)
dat.new$number <- row.names(dat.new)

#merge data frames
#"all = TRUE" will mean that NA values will be added whenever there is no match 
finaldata <- merge(dat, dat.new, by = "number", all = TRUE)
Run Code Online (Sandbox Code Playgroud)