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?

+3


source to share


2 answers


You can multiply each column by a vector, which is 1 if all values ​​are positive in that row and NA otherwise:



df * ifelse(rowSums(df <= 0) > 0, NA, 1)
#    A  B
# 1 NA NA
# 2  2  1
# 3 NA NA

      

+6


source


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

      

+2


source







All Articles