使用 Case when 在 R 中构造一个新变量

Constructing a new variable in R using Case when

正在尝试构造一个新变量,大小 class。规模 class 将基于使用以下结构的就业

     Sizeclass        Employment Range
         1                    1-9
         2                    10-99
         3                    100-499
         4                    500-999

这是一个示例数据集

      acct        Employment
        1             4
        2             12
        3             1
        4             54
        5             234
        6             13
        7             654
        8             101

到目前为止,这是我正在尝试使用的代码

            sizeclass %>%
            select(uiacct, naics, employment) %>%
            mutate(sizeclass = case_when (employment >=1 and employment <9 ~ "1",)
            employment >=10 and employment<=99 ~ "2"))

在互联网上搜索,但几乎没有找到结合 Case_when、变异和不等式的内容。我知道不平等的设置不正确。我的主要问题是这是否是创建这个新变量的正确结构?

注意:所有三个答案都有效。这个网站对 R

的帮助真是太神奇了

尝试以下操作:

df <- data.frame(
  acct = c(1:8),
  employment = c(4,12,1,54,234,13,654,101)
)

df <-  setDT(df)

df <- df[,`:=`(
  Sizeclass = case_when(
    Employment >= 1 & Employment <= 9 ~ 1,
    Employment >= 10 & Employment <= 99 ~ 2,
    Employment >= 100 & Employment <= 499 ~ 3,
    Employment >= 500 & Employment <= 999 ~ 4
  )
)]

如果您的数据集是 'dataframe',则首先将其转换为 'datatable'

这是一个 tidyverse 答案。

sizeclass <- data.frame(
  acct = c(1:8),
  employment = c(4,12,1,54,234,13,654,101)
)

library(tidyverse)

df <- sizeclass %>%
  # select(uiacct, naics, employment) %>%
  mutate(sizeclass = case_when(
    employment %in% c(1:9) ~ "1",
    employment %in% c(10:99) ~ "2",
    employment %in% c(100:499) ~ "3",
    employment %in% c(500:999) ~ "4"))

输出:

  acct employment sizeclass
1    1          4         1
2    2         12         2
3    3          1         1
4    4         54         2
5    5        234         3
6    6         13         2
7    7        654         4
8    8        101         3

我喜欢对 two-way 不等式使用 between() 来给出更整洁的代码:

library(tidyverse)

sizeclass %>%
     select(uiacct, naics, employment) %>%
     mutate(sizeclass = case_when(between(employment, 1, 9) ~ 1,
                                  between(employment, 10, 99) ~ 2,
                                  between(employment, 100, 499) ~ 3,
                                  between(employment, 500, 999) ~ 4)) 

请注意,如果您将 sizeclass 值放在引号 "" 中,您将得到一个 character-type 列。如果您想要数字列,只需使用数字即可。