Home > Enterprise >  Adding a vector to a column, without specifying the other columns
Adding a vector to a column, without specifying the other columns

Time:12-02

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.

CodePudding user response:

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>

CodePudding user response:

You can use the rbindlist() function from the data.table package to add a vector to a column in a data table without specifying the other columns. The rbindlist() function allows you to create a list of vectors or data tables and combine them into a single data table.

In your case, you can create a new vector with the values you want to add to the data table and use the rbindlist() function to append the vector to the data table. For example, the following code shows how to add the vector vector_to_add to the data table dat:

    library(data.table)

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

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

# Create a new vector with the values to add to the data table
new_vector <- c(NA, NA, vector_to_add[1], NA)

# Use rbindlist() to append the new vector to the data table
out <- rbindlist(list(dat, new_vector))

# Add the second value from the vector to the data table
out <- rbindlist(list(out, c(NA, NA, vector_to_add[2], NA)))

After running this code, the data table out should contain the desired output:

   A  B     C     D
1: one 2 three four
2: two 3    NA   one
3: NA NA  five    NA
4: NA NA   six    NA

You can use the rbindlist() function to append multiple vectors to the data table in a similar way.

  • Related