我有两个(或更多)向量,并希望将它们添加到数据帧中,空白空间被NA替换,而不必在向量的声明中指定。这甚至可能吗?
df <- data.frame()
e <- c(1,2,3,4)
q <- c(1,2,3,4,5)
df <- rbind(df, e)
df <- rbind(df, q)
获得
x1 x2 x3 x4 x5
1 1 2 3 4 NA
2 1 2 3 4 5
而不是
x1 x2 x3 x4
1 1 2 3 4
2 1 2 3 4
答案 0 :(得分:0)
#Put all vectors in a list
mylist = list(e, q)
#Find out the length of the vector with most elements
max_length = max(lengths(mylist))
#subset all vectors to extend to the max_length and rbind
data.frame(do.call(rbind, lapply(mylist, function(x) x[1:max_length])))
# X1 X2 X3 X4 X5
#1 1 2 3 4 NA
#2 1 2 3 4 5
主要的技巧是,如果你将一个向量的子集超出它所拥有的实际元素数,那么剩下的元素将是NA
。测试
(1:5)[1:7]
#[1] 1 2 3 4 5 NA NA
答案 1 :(得分:0)
在dplyr::bind_rows
df <- data.frame()
e <- c(1,2,3,4)
q <- c(1,2,3,4,5)
df1 <- rbind(df, e)
df2 <- rbind(df, q)
bind_rows(df1,df2)
X1 X2 X3 X4 X5
1 1 2 3 4 NA
2 1 2 3 4 5