我有必须初始化为空数据框的数据框。现在我只有一列可用,我想将其添加到空数据框中。我该怎么办?我不确定会提前多少列。
例子
df = data.frame(a= NA, b = NA, col1= NA)
....
nrow(col1) # Here I will know length of column, and I only have one column available here.
df$col1 <- col1
错误如下:
Error in `$<-.data.frame`(`*tmp*`, "a", value = c("1", :
替换有5行,数据有1行
任何帮助将是巨大的
用 cbind
df = data.frame(a= NA, b = NA)
col1 <- c(1,2,3,4,5)
df <- cbind(df, col1)
# a b col1
# 1 NA NA 1
# 2 NA NA 2
# 3 NA NA 3
# 4 NA NA 4
# 5 NA NA 5
编辑之后,您仍然可以使用cbind
,但是您需要先删除现有的列(或处理之后的重复列cbind
)
cbind(df[, 1:2], col1)
## or if you don't know the column indeces
## cbind(df[, !names(df) %in% c("col1")], col1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句