chippycentra
chippycentra

Reputation: 879

Add empty rows into a data frame depending ont vector values

I have a vector with two values

v <- c("Sp4","Sp5")

and a data frame such as

col1 col2 col3
Sp1 2 2
Sp2 4 6
Sp3 6 4

and I would like to add NA at this data frame depending on the vector such as:

col1 col2 col3
Sp1 2 2
Sp2 4 6
Sp3 6 4
Sp4 NA NA
SP5 NA NA

I tried:

for (i in v){
  df1[nrow(df1),] <- i
}

Upvotes: 0

Views: 22

Answers (1)

akrun
akrun

Reputation: 887501

We can use bind_rows after creating 'v' as a tibble

library(dplyr)
df1 %>% 
   bind_rows(tibble(col1 = v))
#   col1 col2 col3
#1  Sp1    2    2
#2  Sp2    4    6
#3  Sp3    6    4
#4  Sp4   NA   NA
#5  Sp5   NA   NA

Or with rbind from base R

rbind(df1, data.frame(col1 = v, col2 = NA, col3 = NA))

Upvotes: 1

Related Questions