【问题标题】:Creating Character Variables with data.table使用 data.table 创建字符变量
【发布时间】:2021-12-13 19:50:47
【问题描述】:

假设我们有以下data.table:

x_dt <- data.table(sexn = c(1, 0, 0, 1, NA, 1, NA), 
                   country = c("CHN", "JPN", "BGR",  "AUT", " ", "TWN", " "), 
                   age = c(35, NA, 40, NA, 70, 18, 36)
)

我正在尝试创建一个变量 asia_region,当国家/地区 %chin% c("CHN", "JPN", "KOR", "SGP", "TWN") 时其值为 1,当国家/地区不缺失时其值为 0,而当国家/地区缺失时其值为 NA。

以下代码在缺少国家/地区时填充 0。

result <- x_dt[, asia_region := ifelse(country %chin% c("CHN", "JPN", "KOR",  "SGP", "TWN"),1 , 0)]

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    我们可以使用as.integer+ 直接将逻辑强制转换为二进制,然后通过在i 中指定逻辑条件将值更改为NA,其中“国家”为空白("")和将 'asia_region' 中的那些对应元素分配 (:=) 到 NA

    x_dt[,  asia_region := +(country %chin% c("CHN", "JPN", "KOR", "SGP", "TWN"))]
    x_dt[trimws(country) == "", asia_region := NA_integer_]
    

    -输出

    > x_dt
       sexn country age asia_region
    1:    1     CHN  35           1
    2:    0     JPN  NA           1
    3:    0     BGR  40           0
    4:    1     AUT  NA           0
    5:   NA          70          NA
    6:    1     TWN  18           1
    7:   NA          36          NA
    

    或者,如果我们需要 ifelse/fifelseif/else 无法工作,因为它没有被矢量化,即它需要长度为 1 且不超过该长度的输入表达式)

    x_dt[, asia_region := fifelse(trimws(country) == "", NA_integer_,
            fifelse(country %chin% c("CHN", "JPN", "KOR", "SGP", "TWN"), 1, 0))]
    

    【讨论】:

    • 谢谢。这行得通。有没有更直观的使用“if”、“else if”、“else”语句的解决方案?
    • 我建议从data.table 的角度来看,akrun 的第一个解决方案更加规范和高效。 if 肯定不对,ifelse/fifelse 肯定是不错的选择。 (我建议您按原样接受这个答案,不太可能/将提供更好的解决方案,imo。)
    • 第二种使用 fifelse 的解决方案不需要链接表达式。这不是比第一个更有效率吗?
    • @MKro 不,它不会。我认为第一个更直接,因为它只是一种强制
    【解决方案2】:

    dplyr() 解决方案怎么样?我会制作一个国家的矢量,以便于参考:

    asia_countries <-  c("CHN", "JPN", "KOR",  "SGP", "TWN")
    
    x_dt |>
      dplyr::mutate(asia_region = ifelse(country %in% asia_countries, 1, 0)) |>
      dplyr::mutate(asia_region = ifelse(country == " ", NA, asia_region))
    

    【讨论】:

      猜你喜欢
      • 2014-08-26
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2013-09-23
      • 1970-01-01
      相关资源
      最近更新 更多