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

cli*_*226 2 if-statement nested r dplyr

我想使用 if else 语句根据另一列中的数据在我的数据框中创建一个新列。我已经看过一些先前的文章(例如这个这个),但似乎做错了一些事情,因为我要么收到错误,要么没有新的专栏。

我尝试过制作 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")}
Run Code Online (Sandbox Code Playgroud)

这个函数可以工作/运行,但我不知道如何将它应用到我的数据框中的一列(我已经尝试过这个,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"))
Run Code Online (Sandbox Code Playgroud)

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

任何帮助或指导将不胜感激!

jpd*_*o17 5

我们可以像这样使用 case_when :

\n
library(tidyverse)\n\ndat <- tibble(P.col = seq(0, 20000, 1000))\n\nmutate(dat, P.bin = case_when(P.col >= 4000 ~ ">4000",\n                              P.col <= 3000 & P.col >= 2000 ~ "2000-3000",\n                              P.col <= 3000 & P.col >= 2000 ~ "2000-3000",\n                              P.col <= 2000 & P.col >=1000 ~ "1000-2000",\n                              P.col < 1000 ~ "1000"))\n#> # A tibble: 21 x 2\n#>    P.col P.bin    \n#>    <dbl> <chr>    \n#>  1     0 1000     \n#>  2  1000 1000-2000\n#>  3  2000 2000-3000\n#>  4  3000 2000-3000\n#>  5  4000 >4000    \n#>  6  5000 >4000    \n#>  7  6000 >4000    \n#>  8  7000 >4000    \n#>  9  8000 >4000    \n#> 10  9000 >4000    \n#> # \xe2\x80\xa6 with 11 more rows\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n