0
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.

6
  • You want to do it only for B and C columns leaving A ? Commented Mar 28, 2018 at 4:37
  • Yes only for B and C ) Commented Mar 28, 2018 at 4:38
  • Can the values be negative as well? Or will it be either greater than 0 or 0 ? Commented Mar 28, 2018 at 4:38
  • 1
    d[c("B","C")] <- lapply(d[c("B","C")], >, 0)? Commented Mar 28, 2018 at 4:49
  • 1
    I think this should be a duplicate of some question, couldn't find something close, hence answering. Commented Mar 28, 2018 at 4:55

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

We can use tidyverse

library(dplyr)
d %>%
  mutate_at(2:3, funs(. > 0))
#  A     B     C
#1 1 FALSE FALSE
#2 1  TRUE  TRUE

Comments

-1

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

3 Comments

If B>0 return "TRUE", if not "FALSE"
my point is: your ifelse call returns exactly the same as d$B>0 or actually the same as as.character(d$B>0), which is another part I don't find logical
class("TRUE") vs class(TRUE)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.