Home > Software design >  how to add a row to a df with one var=character(0)
how to add a row to a df with one var=character(0)

Time:08-13

I would like to add a row to an exist df df. the newrow contain the data as below, where V2=nv.

My problem is as nv is character(0), how can I put it in as empty or NA? Is it a good way to bind it together?

I tried rbind(df,newrow, stringsAsFactors=FALSE) as well as df%>% add_row() but could not get it to work. could anyone show me how to do this in both way, if it is possible? Thanks.

df<- structure(list(ID = "S12", 
            Sheet = "Reproductive", 
            TEST = "Y", 
             V1 = NA_character_, 
             V2 = NA_character_), 
class = "data.frame", row.names = c(NA, -1L))

nv <- character(0)

newrow<- nr<- list(ID ="S13",
              Sheet="Test",
              TEST= "N",
              V2= nv,
              V1= "removed")

CodePudding user response:

We can set the elements that have length 0 to NA and then rbind

nr[lengths(nr) == 0] <- NA
rbind(df, nr)

-output

 ID        Sheet TEST      V1   V2
1 S12 Reproductive    Y    <NA> <NA>
2 S13         Test    N removed <NA>

Or as @G.Grothendieck mentioned in the comments, if we don't want to change the original object 'nr', use replace (which internally does the assignment in the function environment and thus it doesn't modify the object)

rbind(df, replace(nr, lengths(nr) == 0, NA))

Or another option is to extract [ the first element, automatically returns NA if length is 0

rbind(df, lapply(nr, `[`, 1))
   ID        Sheet TEST      V1   V2
1 S12 Reproductive    Y    <NA> <NA>
2 S13         Test    N removed <NA>

i.e. we are using index which didn't exist and thus returns the NA

> character(0)[1]
[1] NA
> character(0)[1:2]
[1] NA NA
  •  Tags:  
  • r
  • Related