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 write the same value to multiple entries of an ID in a data frame in R?

My data essentially looks like this, in a much shortened form:

df <- data.frame(id = c(1,1,1,2,2,2,2,2,3,3,3,3), 
                 height = c(150, NA, 151, NA, NA, 176, 175, 174, 198, NA, 197, 198))

What I would like to do is compute the mean height for each of these IDs and then plug that height in for every NA for that given ID. So ID 1 should have a mean height of 150.5, thus the first NA should be replaced by 150.5. Then ID 2 has a mean height of 175, so I’d like to plug in 175 for the two NAs associated with ID 2. And so on.

I know I could manually enter these with things like df[2,2] <- 150.5, but in reality I have thousands of IDs and this wouldn’t be feasible.

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

I’m pretty comfortable with the dplyr package and I figure I should utilize group_by(id) somehow, but I can’t figure out the rest.

Any suggestions?

>Solution :

An approach using replace_na

library(dplyr)
library(tidyr)

df %>% 
  mutate(height_new = replace_na(height, mean(height, na.rm=T)), .by = id)
   id height height_new
1   1    150   150.0000
2   1     NA   150.5000
3   1    151   151.0000
4   2     NA   175.0000
5   2     NA   175.0000
6   2    176   176.0000
7   2    175   175.0000
8   2    174   174.0000
9   3    198   198.0000
10  3     NA   197.6667
11  3    197   197.0000
12  3    198   198.0000
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