Search code examples
rvectordata.tablerbind

Adding a vector to a column, without specifying the other columns


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.


Solution

  • 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>