Replace string with NA if any values ββare non-positive
My dataset is like below:
df <- data.frame(
A = c(-1, 2, 3),
B = c(1, 1, -1))
df
# A B
# 1 -1 1
# 2 2 1
# 3 3 -1
I am trying to get the following result, where the values ββare stored when both A
and B
are positive:
A B
1 NA NA
2 2 1
3 NA NA
I've tried df2 <- apply(df, 1:2, function(x) if (x > 0) x else NA)
but it returns when A
either B
is positive. How do I add a second condition to it?
source to share
replicate(NCOL(df), Reduce('|', lapply(df, function(x) x < 0)))
can give indices where NA
to replace. It checks if there is at least one value less than zero in each column.
replace(df, replicate(NCOL(df), Reduce('|', lapply(df, function(x) x < 0))), NA)
# A B
#1 NA NA
#2 2 1
#3 NA NA
or
df[which(!rowSums(df >= 0) == NCOL(df)),] = NA
df
# A B
#1 NA NA
#2 2 1
#3 NA NA
source to share