Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add a row to a df with one var=character(0)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading