所以我有一个数据帧的一列,其中包含一个值,该值等于不同的列名称。对于每一行,我想更改指定列的值。
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/