Adding a row to a data frame when the row contains more elements than there are columns in the data frame

Viewed 37

I would like to add a new row to a data frame; however, this row in my case has more values. Let's assume I have the following dataset:

> df <- data.frame(0,0,0)
> colnames(df) <- c("A","B","C")
> df
A B C
0 0 0

Now let us have a vector with 4 elements.

> x <- c(0,0,0,0)
> names(x) <- c("A","B","D","C")
> x
A B D C 
0 0 0 0 

I would like to add this vector to the data frame above such that

> df
A B C D
0 0 0 NA 
0 0 0 0 

Is there a way to do this?

2 Answers

You may use -

library(dplyr)

df %>% bind_rows(x %>%
  t %>%
  as.data.frame())

#  A B C  D
#1 0 0 0 NA
#2 0 0 0  0

Or as @Andrew Gustar mentioned -

dplyr::bind_rows(df, x)

Using rbindlist

library(data.table)
rbindlist(list(df, as.data.frame.list(x)), fill = TRUE)
   A B C  D
1: 0 0 0 NA
2: 0 0 0  0
Related