Home > Net >  Add empty row to dataframe from vector with row names in R
Add empty row to dataframe from vector with row names in R

Time:03-28

I have a dataframe like this:

DF =
    C1    C2    C3
R1  9     2     7
R2  4     1     NA
R4  3     5     1 

And I have a vector like this:

V = 
[1] "R3", "R5"

What can I do to add the vector to the dataframe so that the items in the vector becomes row names for new rows with NA values?

The dataframe I am looking to get is this:

DF = 
    C1    C2    C3
R1  9     2     7
R2  4     1     NA
R3  NA    NA    NA 
R4  3     5     1
R5  NA    NA    NA  

Many thanks in advance!

CodePudding user response:

One option to achieve your desired result may look like so. I first append some empty rows, append your vector to the row names and finally order the dataframe by row names:

df <- data.frame(
  C1 = c(9, 4, 3),
  C2 = c(2, 1, 5),
  C3 = c(7, NA, 1),
  row.names = paste0("R", c(1, 2, 4))
)

v <- c("R3", "R5")

rn <- row.names(df)
df[nrow(df)   seq_along(v), ] <- NA 
row.names(df) <- c(rn, v)
df <- df[order(row.names(df)),]
df
#>    C1 C2 C3
#> R1  9  2  7
#> R2  4  1 NA
#> R3 NA NA NA
#> R4  3  5  1
#> R5 NA NA NA

CodePudding user response:

In tidyverse, we can use complete to expand the row name converted column, so that the rest of the columns will be NA for those elements in V

library(dplyr)
library(tidyr)
library(tibble)
df1 %>% 
   rownames_to_column('rn') %>%
   complete(rn = union(rn, V)) %>% 
   column_to_rownames("rn")

-output

   C1 C2 C3
R1  9  2  7
R2  4  1 NA
R3 NA NA NA
R4  3  5  1
R5 NA NA NA  

data

df1 <- structure(list(C1 = c(9, 4, 3), C2 = c(2, 1, 5), C3 = c(7, NA, 
1)), class = "data.frame", row.names = c("R1", "R2", "R4"))
V <- c("R3", "R5")
  • Related