【问题标题】:Recode multiple variables using across, case_when and rec (sjmisc)使用 cross、case_when 和 rec (sjmisc) 重新编码多个变量
【发布时间】:2021-04-28 01:51:19
【问题描述】:

我将从一些示例数据开始:

set.seed(1)
exampledata <- data.frame(
  a = sample(1:5, 10, replace = TRUE),
  b = sample(1:5, 10, replace = TRUE),
  c = sample(1:5, 10, replace = TRUE),
  a_long = sample(1:5, 10, replace = TRUE),
  b_long = sample(1:5, 10, replace = TRUE),
  c_long = sample(1:5, 10, replace = TRUE)
)

当满足原始列的条件时,我正在尝试将列 ac 中的值替换为相应 _long 列中的重新编码值。这完成了我想要的但不能很好地扩展:

library(tidyverse)
library(sjmisc)

exampledata %>%
  mutate(
    a = case_when(
      a %% 2 == 1 ~ rec(a_long, rec = "1=4000; 2=12000; 3=20000; 4=30000; 5=42000"),
      TRUE ~ as.numeric(a)
    ),
    b = case_when(
      b %% 2 == 1 ~ rec(b_long, rec = "1=4000; 2=12000; 3=20000; 4=30000; 5=42000"),
      TRUE ~ as.numeric(b)
    ),
    c = case_when(
      c %% 2 == 1 ~ rec(c_long, rec = "1=4000; 2=12000; 3=20000; 4=30000; 5=42000"),
      TRUE ~ as.numeric(c)
    )
  )

这是我一次对所有列执行此操作的尝试:

exampledata %>%
  mutate(across(c(a, b, c), ~ case_when(
    .x %% 2 == 1 ~ rec(paste0(cur_column(), "_long"), rec = "1=4000; 2=12000; 3=20000; 4=30000; 5=42000"),
    TRUE ~ as.numeric(.x)
  )))

但是,它不使用重新编码的值,而是将NA's 放在满足条件的单元格中。我尝试在paste0(cur_column(), "_long") 之前添加!! 但这会引发错误:

错误:cur_column() 只能在 across() 内部使用。

我的问题本质上是如何将列名粘贴在一起,以便我可以将它们输入rec()

我会参考继续使用rec()case_when(),因为我的真实代码使用多个条件并且有更多值需要重新编码。任何帮助将不胜感激。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    您可以使用map2_dfc 并成对传递列并将case_when 应用于它们。

    library(tidyverse)
    library(sjmisc)
    
    map2_dfc(exampledata %>% select(a:c), 
         exampledata %>% select(ends_with('long')), 
         ~case_when(.x %% 2 == 1 ~ 
                      rec(.y, rec = "1=4000; 2=12000; 3=20000; 4=30000; 5=42000"),
                    TRUE ~ as.numeric(.x))) %>%
      bind_cols(exampledata %>% select(ends_with('long')))
    
    #       a     b     c a_long b_long c_long
    #   <dbl> <dbl> <dbl>  <int>  <int>  <int>
    # 1 30000 20000  4000      4      3      1
    # 2     4 12000     2      4      2      4
    # 3 30000     2     2      4      2      5
    # 4     2     2  4000      2      5      1
    # 5 30000 12000     4      4      2      1
    # 6  4000  4000 30000      1      1      4
    # 7     2 20000     4      1      3      5
    # 8 30000 20000 42000      4      3      5
    # 9  4000 30000     2      1      4      4
    #10 12000 20000     2      2      3      5
    

    【讨论】:

    • 如何在创建exampledata 的更长 dplyr 链中使用它? exampledata %&gt;% map2_dfc(. %&gt;% select(a:b), . %&gt;% select(ends_with('long')), etc) 不起作用。
    • 管道将第一个参数传递给函数。所以你可以这样做:exampledata %&gt;% select(a:c) %&gt;% map2_dfc(exampledata %&gt;% select(ends_with('long')), ~case_when(....)).
    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多