如何在循环中使用mutate和ifelse? [英] How to use mutate and ifelse in a loop?

查看:109
本文介绍了如何在循环中使用mutate和ifelse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是创建虚拟变量,以指示连续变量是超过某个阈值(1)还是低于该阈值(0).我通过几个重复的mutate实现了这一点,我想用一个循环来代替.

What I do is to create dummies to indicate whether a continuous variable exceeds a certain threshold (1) or is below this threshold (0). I achieved this via several repetitive mutates, which I would like to substitute with a loop.

# load tidyverse
library(tidyverse)

# create data
data <- data.frame(x = runif(1:100, min=0, max=100))

# What I do
data <- data %>%
  mutate(x20 = ifelse(x >= 20, 1, 0)) %>%
  mutate(x40 = ifelse(x >= 40, 1, 0)) %>%
  mutate(x60 = ifelse(x >= 60, 1, 0)) %>%
  mutate(x80 = ifelse(x >= 80, 1, 0)) 
  
# What I would like to do
for (i in seq(from=0, to=100, by=20)){
  data %>% mutate(paste(x,i) = ifelse(x >= i, 1,0))
}

谢谢.

推荐答案

Ronak的基数R可能是最好的,但是出于完整性考虑,这是与您最初使用dplyr时类似的另一种方式:

Ronak's base R is probably the best, but for completeness here's another way similar to how you were originally doing it, just with dplyr:

for (i in seq(from=0, to=100, by=20)){
    var <- paste0('x',i)
    data <- mutate(data, !!var := ifelse(x >= i, 1,0))
}

          x x0 x20 x40 x60 x80 x100
1 99.735037  1   1   1   1   1    0
2  9.075226  1   0   0   0   0    0
3 73.786282  1   1   1   1   0    0
4 89.744719  1   1   1   1   1    0
5 34.139207  1   1   0   0   0    0
6 88.138611  1   1   1   1   1    0

这篇关于如何在循环中使用mutate和ifelse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆