是否可以动态改变列(列中的值具有其他列名)

Is it possible to dynamically mutate columns (values in a column have other column names)

所以我有一个数据框的一列,其中包含一个值,该值等于不同的列名。对于每一行,我想更改指定列的值。

df <- tibble(.rows = 6) %>% mutate(current_stage = c("Stage-1", "Stage-1", "Stage-2", "Stage-3", "Stage-4", "Stage-4"), `Stage-1` = c(1,1,1,2,4,5), `Stage-2` = c(40,50,20,10,15,10), `Stage-3` = c(1,2,3,4,5,6), `Stage-4` = c(NA, 1, NA, 2, NA, 3))

A tibble: 6 x 5
current_stage `Stage-1` `Stage-2` `Stage-3` `Stage-4`
<chr>             <dbl>     <dbl>     <dbl>     <dbl>
Stage-1               1        40         1        NA
Stage-1               1        50         2         1
Stage-2               1        20         3        NA
Stage-3               2        10         4         2
Stage-4               4        15         5        NA
Stage-4               5        10         6         3

所以在第一行中,我想编辑 Stage-1 列中的值,因为 current_stage 列有 Stage-1。我试过使用 !!rlang::sym:

df %>% mutate(!!rlang::sym(current_stage) := 15)

但我收到错误:Error in is_symbol(x) : object 'current_stage' not found

这甚至可以做到吗?还是我应该硬着头皮写一个不同的函数?

tidyverse 中,我认为使用 gather 的长格式是 所建议的最简单的方法:

library(tidyverse)

df %>%
  rowid_to_column() %>%
  gather(stage, value, -current_stage, -rowid) %>%
  mutate(value = if_else(stage == current_stage, 15, value)) %>%
  spread(stage, value)
#> # A tibble: 6 x 6
#>   rowid current_stage `Stage-1` `Stage-2` `Stage-3` `Stage-4`
#>   <int> <chr>             <dbl>     <dbl>     <dbl>     <dbl>
#> 1     1 Stage-1              15        40         1        NA
#> 2     2 Stage-1              15        50         2         1
#> 3     3 Stage-2               1        15         3        NA
#> 4     4 Stage-3               2        10        15         2
#> 5     5 Stage-4               4        15         5        15
#> 6     6 Stage-4               5        10         6        15

reprex package (v0.2.1)

于 2019-05-20 创建