r - 应用 if else 条件在 r 中创建新列

标签 r if-statement nested dplyr

我想使用 if else 语句根据另一列中的数据在我的数据框中创建一个新列。我已经查看了一些先前的(例如 this onethis one ),但似乎做错了什么,因为我要么得到错误,要么没有新列。

我试过制作一个 ifelse 函数:

  if(x >= 4000)
{print (">4000")
  } else if (x >=3000 & x <= 4000) 
    {print ("3000-4000")
    } else if  (x >=2000 & x <= 3000) 
    {print("2000-3000")
      } else if (x >=1000 & x <= 2000)
      {print("1000-2000")
      } else print ("<1000")}

此函数有效/运行但我无法弄清楚如何将它应用于我的数据框中的一列(我试过这个 dat$P.bins <- Bins(dat$Pcol) 但出现以下错误:条件的长度 > 1 并且只有第一个将使用元素 1 ">4000"

我还尝试运行 ifelse 语句:

dat$P.bin<- ifelse(P.col>=4000, ">4000",
                                ifelse(P.col <=4000 & >= 3000, "3000-4000"),
                                ifelse(P.col<=3000 & >= 2000, "2000-3000"), 
                                ifelse(P.col <=2000 & >=1000, "1000-2000"), 
                                ifelse(P.col <1000, "1000"))

但出现此错误:错误:意外的 '>=' in:"dat$P.bins <- ifelse(Pcol >=4000, ">4000",felse(Pcol <=4000 & >=". 有了这个语句我不确定如何在 ifelse 语句中做一个范围。

如有任何帮助或指导,我们将不胜感激!

最佳答案

我们可以这样使用 case_when:

library(tidyverse)

dat <- tibble(P.col = seq(0, 20000, 1000))

mutate(dat, P.bin = case_when(P.col >= 4000 ~ ">4000",
                              P.col <= 3000 & P.col >= 2000 ~ "2000-3000",
                              P.col <= 3000 & P.col >= 2000 ~ "2000-3000",
                              P.col <= 2000 & P.col >=1000 ~ "1000-2000",
                              P.col < 1000 ~ "1000"))
#> # A tibble: 21 x 2
#>    P.col P.bin    
#>    <dbl> <chr>    
#>  1     0 1000     
#>  2  1000 1000-2000
#>  3  2000 2000-3000
#>  4  3000 2000-3000
#>  5  4000 >4000    
#>  6  5000 >4000    
#>  7  6000 >4000    
#>  8  7000 >4000    
#>  9  8000 >4000    
#> 10  9000 >4000    
#> # … with 11 more rows

reprex package 创建于 2021-06-11 (v2.0.0)

关于r - 应用 if else 条件在 r 中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67943039/

相关文章:

r - 使用 broom 和 tidyverse 对不同的因变量运行回归

r - 如何将字符转换为ASCII码?

python - 在if条件下使用两个任意功能时出错

C 中嵌套 for 循环中的条件不起作用

python - 具有深度值的镜像列表,到嵌套列表 ~ Python

css - Bootstrap - 嵌套的最佳实践 - 行和跨度

r - 如何返回 R 中两个 data.frames 之间匹配行的索引

r - 使用矩阵值作为索引

javascript - 为什么这段代码会导致无限循环?

ruby-on-rails - 不允许的参数 : nested forms