I have would like to add a vector to a column, without specifying the other columns. I have example data as follows.

library(data.table)
dat <- fread("A B C D
              one 2 three four
              two 3 NA    one")

vector_to_add <- c("five", "six")

Desired ouput:

out <- fread("A B C D
              one 2 three four
              two 3 NA    one
              NA  NA five  NA
              NA  NA six   NA")

I saw some answers using an approach where vectors are used to rowbind:

row3 < c(NA, NA, "five", NA)

I would however like to find a solution in which I do not have specify the whole row.

EDIT: Shortly after posting I realised that it would probably be easiest to take an existing row, make the row NA, and replace the value in the column where the vector would be added, for each entry in the vector. This is however still quite a cumbersome solution I guess.

推荐答案

If you name your vector, then you can rbind that column and fill the rest of the cells with NAs.

df_to_add <- data.frame(C=c("five", "six"))
rbind(dat, df_to_add, fill=TRUE)
      A  B     C    D
1:  one  2 three four
2:  two  3  <NA>  one
3: <NA> NA  five <NA>
4: <NA> NA   six <NA>

R相关问答推荐

如何使用stat_extract_all正确提取我的目标值?

矩阵%*%矩阵中的错误:需要数字/复杂矩阵/向量参数

在R中替换函数中的特定符号

为什么横向页面会导致officeverse中的页码/节头/页脚出现问题?

将非重复序列高效转换为长格式

然后根据不同的列值有条件地执行函数

如何在modelsummary中重命名统计数据?

二维样条,严格以一个参数递增

为什么舍入POSIXct会更改能力以匹配等效的POSIXct?

将多列合并为单独的名称—值对

将重复项转换为NA

当我添加美学时,geom_point未对齐

如何删除R中除数字元素以外的所有元素

R仅当存在列时才发生变异

如何在R中创建条形图,使条形图在y轴上围绕0.5而不是0构建条形图?

如何在R中添加标识连续日期的新列

带有Bootswatch Cerulean主题的shiny 仪表板中的浏览&按钮可见性问题

如果y中存在x中的值,则将y行中的多个值复制到相应的x行中

使用相对风险回归计算RR

当R使用c()组合两个向量时会发生什么?