R中的嵌套if-else循环 [英] Nested if-else loops in R

查看:896
本文介绍了R中的嵌套if-else循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"crimes"的数据框,其中包含一个"pre_rate"列,该列表示在实施某些法律之前的犯罪率.我想使用嵌套的if-else循环将每个速率放入"rate_category"列中.我有以下代码:

I have a data frame named "crimes" which contains a "pre_rate" column that denotes the crime rate before a certain law is implemented. I would like to put each rate in a "rate_category" column using a nested if-else loop. I have the following code:

crimes$rate_category = 
  with(crimes, ifelse(pre_rate > 0.26 && pre_rate < 0.87, 1,
    ifelse(pre_rate > 1.04 && pre_rate < 1.94, 2, 
      ifelse(pre_rate > 2.03 && pre_rate < 2.96, 3, 
        ifelse(pre_rate > 3.10 && pre_rate < 3.82, 4, 
          ifelse(pre_rate > 4.20 && pre_rate < 11.00, 5, "NA"))))))
crimes

这是一个可复制的示例:

and here's a reproducible example:

pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80) 
crimes = data.frame(pre_rate)   
crimes

但是,当我使用原始数据帧运行循环时,"rate_category"列中的所有级别均错误地设置为1.上面的循环似乎是什么问题?

However, when I run the loop with my original data frame, all levels in the "rate_category" column is incorrectly set to 1. What seems to be the problem with the loop above?

推荐答案

我可能建议使用case_when而不是嵌套ifelse语句.阅读/遵循它要容易一些.但是正如@Marius所提到的,您的问题是&&而不是使用&.

Instead of nesting ifelse statements might I recommend using case_when. It is a bit easier to read/follow. But as @Marius mentioned your problem is the && instead of using &.

library(tidyverse)
crimes <- data.frame(pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80))

crimes %>% 
  mutate(rate_category = case_when(pre_rate > 0.26 & pre_rate < 0.87 ~ 1,
                                   pre_rate > 1.04 & pre_rate < 1.94 ~ 2,
                                   pre_rate > 2.03 & pre_rate < 2.96 ~ 3,
                                   pre_rate > 3.10 & pre_rate < 3.82 ~ 4,
                                   pre_rate > 4.20 & pre_rate < 11.00 ~ 5))

这篇关于R中的嵌套if-else循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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