简体   繁体   English

在 mutate 语句中动态引用列名 - dplyr

[英]Refer to column names dynamically inside mutate statements - dplyr

I stat apologize for the long question, but after quite a while I couldn't figure out a solution myself.我为这个冗长的问题道歉,但过了一段时间我自己也想不出解决方案。

I have this toy dataframe我有这个玩具 dataframe

set.seed(23)
df <- tibble::tibble(
  id = paste0("00", 1:6),
  cond = c(1, 1, 2, 2, 3, 3),
  A_1 = sample(0:9, 6, replace = TRUE), A_2 = sample(0:9, 6, replace = TRUE), A_3 = sample(0:9, 6, replace = TRUE),
  B_1 = sample(0:9, 6, replace = TRUE), B_2 = sample(0:9, 6, replace = TRUE), B_3 = sample(0:9, 6, replace = TRUE),
  C_1 = sample(0:9, 6, replace = TRUE), C_2 = sample(0:9, 6, replace = TRUE), C_3 = sample(0:9, 6, replace = TRUE)
)

# A tibble: 6 x 11
#   id     cond   A_1   A_2   A_3   B_1   B_2   B_3   C_1   C_2   C_3
#   <chr> <dbl> <int> <int> <int> <int> <int> <int> <int> <int> <int>
# 1 001       1     6     3     9     5     0     5     6     0     6
# 2 002       1     4     5     0     8     5     0     1     6     6
# 3 003       2     4     2     8     8     8     6     5     2     5
# 4 004       2     4     4     0     7     2     6     7     5     7
# 5 005       3     1     7     0     9     9     0     5     7     8
# 6 006       3     3     8     7     0     2     5     0     9     4

I would like to create three variables A_def , B_def , C_def that take the values of only one of the corresponding variables < LETTER_NUMBER > depending on the condition that their suffix is equal to variable cond .我想创建三个变量A_defB_defC_def ,它们仅取对应变量 < LETTER_NUMBER > 之一的值,具体取决于它们的后缀等于变量cond的条件。

For instance, for the rows where cond == 1 , A_def should have values from A_1 , B_def should have values from B_1 , C_def should have values from C_1 .例如,对于cond == 1的行, A_def应该具有来自A_1的值, B_def应该具有来自B_1的值, C_def应该具有来自C_1的值。 Likewise, if cond == 2 , the *_def columns should have values from the respective *_2 variables.同样,如果cond == 2*_def列应该具有来自相应*_2变量的值。

I managed to achieve my desired output in two ways: one hard-coded (possibly to avoid if cond contains many values) and one using tidyr 's pivoting functions.我设法通过两种方式实现了我想要的 output :一种是硬编码(如果cond包含许多值,可能会避免),另一种是使用tidyr的旋转功能。

Hard-coded solution:硬编码解决方案:

df %>% 
  mutate(
    A_def = ifelse(cond == 1, A_1, ifelse(cond == 2, A_2, A_3)),
    B_def = ifelse(cond == 1, B_1, ifelse(cond == 2, B_2, B_3)),
    C_def = ifelse(cond == 1, C_1, ifelse(cond == 2, C_2, C_3))
  ) %>% 
  select(id, cond, contains("_def"))

tidyr 's solution: tidyr的解决方案:

df %>% 
  pivot_longer(cols = contains("_")) %>% 
  mutate(
    number = gsub("[A-Za-z_]", "", name),
    name = gsub("[^A-Za-z]", "", name)
  ) %>% 
  filter(cond == number) %>% 
  pivot_wider(id_cols = c(id, cond), names_from = name, values_from = value, names_glue = "{name}_def")

Output in both cases Output 在两种情况下

# A tibble: 6 x 5
#   id     cond A_def B_def C_def
#   <chr> <dbl> <int> <int> <int>
# 1 001       1     6     5     6
# 2 002       1     4     8     1
# 3 003       2     2     8     2
# 4 004       2     4     2     5
# 5 005       3     0     0     8
# 6 006       3     7     5     4

Now, I was wondering whether it is possible to obtain the same output using mutate and/or across in a dynamic fashion (maybe using ifelse statements inside mutate ?).现在,我想知道是否有可能使用mutate和/或以动态方式交叉获得相同的across (也许在mutate中使用ifelse语句?)。 I tried the following code snippets but the results were not as expected.我尝试了以下代码片段,但结果不如预期。 In one of them I tried to make the variable names as symbols within ifelse statements, but I got an error.在其中一个中,我尝试将变量名称作为ifelse语句中的符号,但出现错误。

df %>% 
  mutate(across(paste0(c("A", "B", "C"), "_1"),
                ~ifelse(cond == 1, cur_column(), 
                        ifelse(cond == 2, cur_column(), paste0(gsub("[^A-Za-z]", "", cur_column()), "_3"))))) %>% 
  select(id, cond, contains("_1"))

df %>% 
  mutate_at(paste0(c("A", "B", "C"), "_1"),
            ~ifelse(cond == 1, ., ifelse(cond == 2, ., paste0(., "_2")))) %>% 
  select(id, cond, contains("_1"))

df %>% 
  mutate_at(paste0(c("A", "B", "C"), "_1"),
            ~ifelse(cond == 1, !!!rlang::syms(paste0(c("A", "B", "C"), "_1")),
                    ifelse(cond == 2, !!!rlang::syms(paste0(c("A", "B", "C"), "_2")),
                           !!!rlang::syms(paste0(c("A", "B", "C"), "_3")))))

Question: is there a way to obtain the same desired output as above using dplyr 's statements such as mutate (or its superseded scoped variants) and/or across ?问题:有没有办法使用dplyr的语句(例如mutate (或其被取代的范围变体)和/或cross )获得与上述相同的所需across

As Ronak said, your tidyr solution seems quite fine.正如 Ronak 所说,您的tidyr解决方案似乎很好。

You can simplify it a bit though:你可以稍微简化一下:

df %>% 
  pivot_longer(cols = contains("_"), names_to = c("name", "number"), names_sep = "_") %>% 
  filter(cond == number) %>% 
  pivot_wider(id_cols = c(id, cond), names_glue = "{name}_def")


## A tibble: 6 x 5
#  id     cond A_def B_def C_def
#  <chr> <dbl> <int> <int> <int>
#1 001       1     7     8     1
#2 002       1     2     5     2
#3 003       2     4     2     3
#4 004       2     0     3     1
#5 005       3     9     0     7
#6 006       3     9     7     0

I agree with the other comments that tidyr makes for more readable code, but here's an alternative approach with pmap :我同意tidyr为提高代码的可读性所做的其他评论,但这是pmap的另一种方法:

library(purrr)
library(rlang)
pmap_dfr(df, ~with(list(...), 
               set_names(c(id, cond, 
                           map_dbl(c("A","B","C"),
                                 ~ eval_tidy(parse_expr(paste(.x,cond,sep = "_"))))),
                          c("id","cond","A_def","B_def","C_def"))
               ))
# A tibble: 6 x 5
     id  cond A_def B_def C_def
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     1     6     5     6
2     2     1     4     8     1
3     3     2     2     8     2
4     4     2     4     2     5
5     5     3     0     0     8
6     6     3     7     5     4

Here's a short base R solution using mapply :这是使用mapply的简短基础 R 解决方案:

f <- function(x, i) df[-(1:2)][i, c(x, x+3, x+6)]
df <- cbind(df[1:2], t(mapply(f, df$cond, seq(nrow(df)))))
setNames(df, c("id", "cond", "A_def", "B_def", "C_def"))
#>    id cond A_def B_def C_def
#> 1 001    1     7     8     1
#> 2 002    1     2     5     2
#> 3 003    2     4     2     3
#> 4 004    2     0     3     1
#> 5 005    3     9     0     7
#> 6 006    3     9     7     0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM