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

Chaning values to NA based on multiple columns

I have a data frame where I wish to change any values from a 0 to an NA but only of the values of paired columns are both 0. I have attached an example below of what I currently have and what I am trying to return. I think to do this its best to pair off the columns we want to check? then once we have identified the positions we want we can simply replace the 0s with NAs. I also thought there might be a way we couple use something like sapply but wasn’t sure how we could pair off columns ‘a’ and columns ‘b’.

df
a1   a2    b1   b2
1     3    0    6
7     9    0    0    
5     5    4    6    
0     0    0    0     
0     0    6    0     

What I’m trying to achieve;

newdf
a1   a2    b1   b2
1     3    0    6
7     9    NA    NA    
5     5    4    6    
NA    NA   NA   NA     
NA    NA   6    0  

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

>Solution :

How about this:

unname(split.default(quux, sub("\\d", "", names(quux)))) |>
  lapply(function(z) { z[rowSums(z > 0) == 0,] <- NA; z; }) |>
  do.call(cbind, args = _)
#   a1 a2 b1 b2
# 1  1  3  0  6
# 2  7  9 NA NA
# 3  5  5  4  6
# 4 NA NA NA NA
# 5 NA NA  6  0

Data

quux <- structure(list(a1 = c(1L, 7L, 5L, 0L, 0L), a2 = c(3L, 9L, 5L, 0L, 0L), b1 = c(0L, 0L, 4L, 0L, 6L), b2 = c(6L, 0L, 6L, 0L, 0L)), class = "data.frame", row.names = c(NA, -5L))
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