跨多列使用和/或条件重新编码
我想创建一个新变量 (new_var) 并根据多个列对其进行条件限制: class == "yes" &分数1:分数5>80。我有可以在下面运行的代码,但是有没有更干净的方法来做到这一点?我通过嵌入多个 ifelse 列来做到这一点,但是有没有一种方法可以让我可以只执行 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))))))
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))))))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你可以或结合条件:
Well you could or together the conditions: