Mr. Buster
Mr. Buster

Reputation: 131

If else logic for single column in data frame then apply to all columns

How can I make in data frame if certain condition applies to a single column then all rows for that data frame will be Null.

For example I had a data frame.

A<- c(2,3,5,6,5,7,8,5)
B <- c("AB", "BC", "CD", "DE", "EF", "FG", "HI", "IJ")
C <- c("X", "Y", "Z", "W", "X", "Y", "Z", "W")
ABC <-data.frame(A,B,C)
> ABC
  A  B C
1 2 AB X
2 3 BC Y
3 5 CD Z
4 6 DE W
5 5 EF X
6 7 FG Y
7 8 HI Z
8 5 IJ W

And I want for every ABC$A equals to 5, then all rows connects with 5 will be NULL or NA.

My desired output should look like this

> ABC
  A    B    C
1 2   AB    X
2 3   BC    Y
3 5 <NA> <NA>
4 6   DE    W
5 5 <NA> <NA>
6 7   FG    Y
7 8   HI    Z
8 5 <NA> <NA>

ifelse function could make this work but what if I had a lot of columns. And I want it to apply to all columns besides A.

Upvotes: 0

Views: 37

Answers (2)

akrun
akrun

Reputation: 886978

We can use na_if

library(dplyr)
ABC %>%
     mutate_at(-1, list(~ na_if(A, y = 5)))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388817

You could use row/column subsetting and assign NAs to all columns directly.

ABC[ABC$A == 5, -1] <- NA

ABC
#  A    B    C
#1 2   AB    X
#2 3   BC    Y
#3 5 <NA> <NA>
#4 6   DE    W
#5 5 <NA> <NA>
#6 7   FG    Y
#7 8   HI    Z
#8 5 <NA> <NA>

Here -1 is to ignore first column A since we do not want to change any values in that column.


Some other variations

ABC[-1] <- lapply(ABC[-1], function(x) replace(x, ABC$A == 5, NA))

and using dplyr

library(dplyr)
ABC %>%  mutate_at(-1, ~replace(., A == 5, NA))

Upvotes: 1

Related Questions