绑定具有不同行数的列

时间:2018-04-06 20:56:29

标签: 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)
}

简化,假设我有

df
1  3
3  4
2  2

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

 df
    1  3  5
    3  4  6
    2  2  NA

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

df
   1  3  5  7
   3  4  6  7
   2  2  NA 7
   NA NA NA 8

我该怎么做?

4 个答案:

答案 0 :(得分:2)

如果您知道df的最大可能大小以及要追加的列总数,则可以使用所有NA值预先创建df,并根据其长度填充列。这将使其长度之后的所有内容仍为NA。

e.g。

max_col_num <- 20 
max_col_size <- 10 #This could be the number of rows in the largest dataframe you have

df <- as.data.frame(matrix(ncol = max_col_num, nrow = max_col_size))

for(i in 1:20){
      temp_seq=another_df$c1[some conditions] 
      df[c(1:length(temp_seq), i] <- temp_seq
}

只有在您新增可能的行数和列数时才会有效。

答案 1 :(得分:2)

这是一种方式。设计合并功能将在组合数据帧时添加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)

答案 2 :(得分:1)

我认为最好的方法是编写一个基于nrow数据框和length向量/列表的自定义函数。

一旦这样的功能可以写成:

#Function to add vector as column
addToDF <- function(df, v){
 nRow <- nrow(df)
 lngth <- length(v)
 if(nRow > lngth){
   length(v) <- nRow
 }else if(nRow < lngth){
   df[(nRow+1):lngth, ] <- NA
 }
 cbind(df,v)
}

让我们用OP提供的data.frame测试上面的函数。

df <- data.frame(A= c(1,3,2), B = c(3, 4, 2))

v <- c(5,6)

w <-c(7,7,8,9)

addToDF(df, v)
#   A B  v
# 1 1 3  5
# 2 3 4  6
# 3 2 2 NA

addToDF(df, w)
#    A  B v
# 1  1  3 7
# 2  3  4 7
# 3  2  2 8
# 4 NA NA 9

答案 3 :(得分:0)

根据 MKRs 的响应,如果您想为新添加的列添加特定名称,您可以尝试:


addToDF <- function(df, v, col_name){
  nRow <- nrow(df)
  lngth <- length(v)
  if(nRow > lngth){
    length(v) <- nRow
  }else if(nRow < lngth){
    df[(nRow+1):lngth, ] <- NA
  }
  df_new<-cbind(df,v)
  colnames(df_new)[ncol(df_new)]=col_name
  return(df_new)
}

其中 col_name 是新添加的列。

相关问题