我试图逐行填充data.frame(或类似的东西)(每次一条记录)。我的问题:
我尝试做的是构建一个包含一行并插入向量的data.frame。
示例:
ddf <- data.frame("1", "2", "3", "4", stringsAsFactors = FALSE)
colnames(ddf) <- c("A","B","C","D")
View(ddf)
data_vector1 <- c("11","22","44")
names(data_vector1) <- c("A","B","D")
data_vector2 <- c("111","222","555")
names(data_vector2) <- c("A","B","E")
#What I want:
# A B C D E
# 1 2 3 4 NA
# 11 22 NA 44 NA
# 111 222 NA NA 555
#Still now
samecols <- intersect(colnames(ddf),names(data_vector1))
ddf <- rbind(ddf, data_vector1[samecols])
#I'm getting:
#A B C D
#1 2 3 4
#11 22 44 11
答案 0 :(得分:1)
我们可以将数据集放在assert.equal
中,转换为list
并将data.frame
与rbindlist
fill=TRUE
或使用library(data.table)
lst <- lapply(list(ddf, data_vector1, data_vector2), as.data.frame.list)
rbindlist(lst, fill=TRUE)
# A B C D E
#1: 1 2 3 4 NA
#2: 11 22 NA 44 NA
#3: 111 222 NA NA 555
bind_rows
dplyr