1

I want to create a new variable (new_var) and condition it off of multiple columns: class == "yes" & score1:score5 >80. I have code that works below but is there a cleaner way to do this? I do it by embedding multiple ifelse columns, but is there a way I can somehow where I can just do score1:score5 > 80?

age <- sample(18:30, 50, replace=TRUE)
score1 <- sample(1:100, 50, replace=TRUE)
score2 <-sample(1:100, 50, replace=TRUE)
score3 <-sample(1:100, 50, replace=TRUE)
score4 <-sample(1:100, 50, replace=TRUE)
score5 <-sample(1:100, 50, replace=TRUE)
year <- sample(c("first", "second", "third", "fourth"), 50, replace=TRUE)
major <- sample(c("ps", "cs", "ir", "stats"), 50, replace =TRUE)
attend <- sample(c("yes", "no"), 50, replace=TRUE)
class <- data.frame(age, score1, score2, score3, score4, score5, year, major, attend)
class <- class %>% mutate(new_var = ifelse(
attend == "yes" & score1 > 80, "good",
ifelse(attend == "yes" & score2 > 80, "good", 
ifelse(attend == "yes" & score3 > 80, "good",
ifelse(attend == "yes" & score4 > 80, "good",
ifelse(attend == "yes" & score5 > 80,  "good",
attend))))))
SaraFormula
  • 61
  • 1
  • 6

1 Answers1

0

Well you could or together the conditions:

class <- class %>% mutate(new_var = ifelse(
    attend == "yes" & (score1 > 80 | score2 > 80 | score3 > 80 | score4 > 80 |
                       score5 > 80), "good",
    attend)
)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360