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

标签 r dplyr tidyverse rlang

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

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)

但我收到错误:is_symbol(x) 中的错误:找不到对象“current_stage”

这可能吗?或者我应该硬着头皮写一个不同的函数?

最佳答案

tidyverse中,我认为使用长格式与gather是最简单的方法,如Jack Brookes所建议的那样。 :

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于2019年5月20日创建(v0.2.1)

关于r - 是否可以动态改变列(列中的值具有其他列名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228647/

相关文章:

regex - 使用 dplyr 在选定的列上添加具有行均值的列

html - 使滚动条出现在 RMarkdown 代码块中(html View )

r - 在 R 中创建唯一 ID 列

r - 分组 data.fame 后的自定义函数

r - 如何更改ggplot对象中所有文本相对于当前值的字体大小?

r - 如何整齐地组合稀疏列

r - 对 R 中每列的矩阵行执行成对统计测试

R:使用带有附加列表的 mapply 作为参数

建模前减少因子水平数量

r - 如何在r中创建多个pivot_longer()列?