d = data.frame(A=c(1,1),B=c(0,20),C=c(0,10))
d$B[d$B>0] = TRUE
d$C[d$C>0] = TRUE
d$B[d$B==0] = FALSE
d$C[d$C==0] = FALSE
Is there a way to do the 4 last operations in one line to simplify things like an if else statement for dataframe.
We can compare the entire dataframe (except the first column) and check if the value is greater than 0 or not and convert that value into numeric
d[-1] <- as.numeric(d[-1] > 0)
d
# A B C
#1 1 0 0
#2 1 1 1
Or if we want to keep the values as logical we can remove the as.numeric call
d[-1] <- d[-1] > 0
# A B C
#1 1 FALSE FALSE
#2 1 TRUE TRUE
You can use dplyr's if_else as follows:
library(dplyr)
d = data.frame(A=c(1,1),B=c(0,20),C=c(0,10))
d$B<-if_else(d$B>0,"TRUE","FALSE")
d$C<-if_else(d$C>0,"TRUE","FALSE")
A B C
1 1 FALSE FALSE
2 1 TRUE TRUE
BandCcolumns leavingA?d[c("B","C")] <- lapply(d[c("B","C")],>, 0)?