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

calculating new columns with NA in starting columns

I have data.frame(col1 = 1:4, col2 = c(NA,1,2,3), col3 = 5:8)

enter image description here

and want to create extra columns which is based on computations involving the other columns with NA in it, but keep getting NA as a result. I do not want to see NA, but want to see 1, based on df %>% mutate( new = .[[1]] + .[[2]])

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

enter image description here

Any suggestions how to work through this? I would prefer to stay using tidyverse and dplyr

>Solution :

Here’s a possible framework: replace NA with 0s, do your calculations, and then use rows_update to replace the original NAs.

library(dplyr)
df %>% 
  replace(is.na(.), 0) %>% 
  mutate(new = .[[1]] - .[[2]]) %>% 
  rows_update(df)

  col1 col2 col3 new
1    1   NA    5   1
2    2    1    6   1
3    3    2    7   1
4    4    3    8   1
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