Home > OS >  Add empty row if element in list not present within a column in R
Add empty row if element in list not present within a column in R

Time:02-26

I have a dataframe such as :

Names G1 G2 G3 
SP1   A  B  C
SP2   D  E  F
SP4   G  H  I

and a list of names such as ;

list_of_names<-c("SP1","SP2","SP3","SP4")

How could I add empty row from element within list_of_names not present within the dataframe such as;

Names G1 G2 G3 
SP1   A  B  C
SP2   D  E  F
SP4   G  H  I
SP3   0  0  0 

CodePudding user response:

We could use complete

library(tidyr)
complete(df1, Names = list_of_names, fill = list(G1 = '0', G2 = '0', G3 = '0'))

-output

# A tibble: 4 × 4
  Names G1    G2    G3   
  <chr> <chr> <chr> <chr>
1 SP1   A     B     C    
2 SP2   D     E     F    
3 SP3   0     0     0    
4 SP4   G     H     I    

Or another option is a join

full_join(df1, tibble(Names = list_of_names))

data

df1 <- structure(list(Names = c("SP1", "SP2", "SP4"), G1 = c("A", "D", 
"G"), G2 = c("B", "E", "H"), G3 = c("C", "F", "I")),
 class = "data.frame", row.names = c(NA, 
-3L))
  • Related