跨多列使用和/或条件重新编码

发布于 2025-01-15 05:50:22 字数 1096 浏览 5 评论 0原文

我想创建一个新变量 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑白记忆 2025-01-22 05:50:22

好吧,你可以或结合条件:

class <- class %>% mutate(new_var = ifelse(
    attend == "yes" & (score1 > 80 | score2 > 80 | score3 > 80 | score4 > 80 |
                       score5 > 80), "good",
    attend)
)

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)
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文