gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:22:09 24 4
gpt4 key购买 nike

我想使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com