【问题标题】:Using ifelse statement for multiple values in a column对列中的多个值使用 ifelse 语句
【发布时间】:2017-03-12 20:05:57
【问题描述】:

我有一个大约 3000 行的表格,其中的数据格式为:

Number  Type
10001   0
10005   7
10006   0
10007   14
10012   16
10022   14
10023   0
10024   0
10029   7
10035   17
10045   14

我想添加第三列,使表格看起来像:

Number  Type   SCHEach
10001   0         0
10005   7         0
10006   0         0
10007   14        0
10012   16        1
10022   14        0
10023   0         0
10024   0         0
10029   7         0
10035   17        1
10045   14        0

其中 SCHEach 列中的值基于 Type 列中的值。如果 Type 列中的值为 16、17、21 或 22,则 SCHeach 列中的值应为 1。对于 Type 列中的任何其他值,SCHEach 值应为 0。

现在我正在使用以下

library(dplyr)
schtable$SCHEach = ifelse(
schtable$Type == 16 | 
schtable$Type == 17 | 
schtable$Type == 21 | 
schtable$Type == 22, 1, 0)

我是 R 新手,想知道是否有办法做到这一点,而不必分别为 16、17、21 和 22 键入以下内容?

schtable$Type == 'number'

【问题讨论】:

  • 阅读%in%,在控制台中输入?match
  • 试试schtable <- schtable %>% mutate(SCHEac = if_else(Type %in% c(16,17,21,22), 1, 0))
  • 谢谢! @zx8754 效果很好。
  • 你不需要ifelse schtable %>% mutate(SCHEac = as.integer(Type %in% c(16, 17, 21, 22)))

标签: r if-statement dplyr


【解决方案1】:
> mydf$SCHEach <- ifelse(mydf$Type %in% c(16,17,21,22),1,0)
> mydf
   Number Type SCHEach
1   10001    0       0
2   10005    7       0
3   10006    0       0
4   10007   14       0
5   10012   16       1
6   10022   14       0
7   10023    0       0
8   10024    0       0
9   10029    7       0
10  10035   17       1
11  10045   14       0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多