Shahin
Shahin

Reputation: 1316

Changing rows with certain column values

I have a data frame with 3 columns $a (char), $b (char), and $c (int).

   a       b     c
1  NA      NA    NA
2  NA    Donald  0
3  shawn  john   120
.
.
.

I would like to replace the rows where df$c==0 and df$a==NA but keep df$b as is. I want something like df[df$a && df$c==0 ==NA] <- c("IGNORED",same as before,"IGNORED")

So my second row will become

2  IGNORED  Donald  IGNORED

I have to use column names, and not column numbers. Is there a package you recommend? Or the base functions would do?

Upvotes: 0

Views: 39

Answers (1)

user2474226
user2474226

Reputation: 1502

You could first get all the rows where your condition holds:

replaces <- which(is.na(df$a) & df$c == 0)

Then update the 'a' and 'c' fields, leaving 'b' unchanged:

df[replaces,]$a <- 'IGNORED'
df[replaces,]$c <- 'IGNORED'

Upvotes: 1

Related Questions