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

Fill NA in R: imput NA in a column X with values from same ID (column Y ) correspondance

I´ve got this dataset (something like below)

db <- as.data.frame(cbind(c(1,2,2,3,3,4,4,4,5,5),c('a','b',NA,NA,'i',NA,'d',NA, NA, NA)))

I´d like to fill the V2 NA with same correpondance from ID column V1.
At the end I expect this result

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

db <- as.data.frame(cbind(c(1,2,2,3,3,4,4,4,5,5),c('a','b','b','i','i','d','d','d', NA, NA)))

I´ve tried to make a list with unique ID
db_aux <- as.data.frame(cbind(c(1,2,3,4),c('a','b','i','d')))

but I guess it´s necessary an apply function to fill in what´s left but i´m not figuring how to indicate the corresponding indexation.
If anyone could be so kind to point the way to solve this question I thank you in advance.

>Solution :

You can use fill from tidyr with the direction being updown or downup.

library(tidyverse)

db %>%
   group_by(V1) %>%
   fill(V2, .direction = 'updown')

# A tibble: 10 x 2
# Groups:   V1 [5]
   V1    V2   
   <chr> <chr>
 1 1     a    
 2 2     b    
 3 2     b    
 4 3     i    
 5 3     i    
 6 4     d    
 7 4     d    
 8 4     d    
 9 5     NA   
10 5     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