如何在 R 中动态改变数据框中的列
How to mutate a column in a dataframe dynamically in R
我想改变定义为变量 (col_name
) 的 dataframe
/tibble
列的值。我试过 !!col_name
但没有成功。
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
col_name <- "b" # the column to select
df <- tibble(a = c(1,2,3), b = c(2,4,6))
df %>%
mutate(b = if_else((b == 6 & a == 3), 8, b)) # this works
#> # A tibble: 3 x 2
#> a b
#> <dbl> <dbl>
#> 1 1 2
#> 2 2 4
#> 3 3 8
# but this doesn't
df %>%
mutate(!!col_name := if_else((!!col_name == 6 & a == 3), 8, !!col_name))
#> Error: Problem with `mutate()` input `b`.
#> x `false` must be a double vector, not a character vector.
#> i Input `b` is `if_else(("b" == 6 & a == 3), 8, "b")`.
Created on 2020-10-13 by the reprex package (v0.3.0)
要在 RHS 上使用 !!
,您需要先将 col_name
转换为符号。
library(dplyr)
df %>% mutate(!!col_name := if_else(!!sym(col_name) == 6 & a == 3,
8, !!sym(col_name)))
其他替代方法包括使用 get
:
df %>% mutate(!!col_name := if_else(get(col_name) == 6 & a == 3,
8, get(col_name)))
或不使用任何 NSE .data
:
df %>% mutate(!!col_name := if_else(.data[[col_name]] == 6 & a == 3,
8, .data[[col_name]]))
使用基础:
df[ df[, col_name ] == 6 & df$a == 3, col_name ] <- 8
df
# a b
# 1 1 2
# 2 2 4
# 3 3 8
注意: 是的,我知道问题是关于 "整洁",这只是为了说明为什么一些简单的任务基础解决方案就像 good/better.
我想改变定义为变量 (col_name
) 的 dataframe
/tibble
列的值。我试过 !!col_name
但没有成功。
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
col_name <- "b" # the column to select
df <- tibble(a = c(1,2,3), b = c(2,4,6))
df %>%
mutate(b = if_else((b == 6 & a == 3), 8, b)) # this works
#> # A tibble: 3 x 2
#> a b
#> <dbl> <dbl>
#> 1 1 2
#> 2 2 4
#> 3 3 8
# but this doesn't
df %>%
mutate(!!col_name := if_else((!!col_name == 6 & a == 3), 8, !!col_name))
#> Error: Problem with `mutate()` input `b`.
#> x `false` must be a double vector, not a character vector.
#> i Input `b` is `if_else(("b" == 6 & a == 3), 8, "b")`.
Created on 2020-10-13 by the reprex package (v0.3.0)
要在 RHS 上使用 !!
,您需要先将 col_name
转换为符号。
library(dplyr)
df %>% mutate(!!col_name := if_else(!!sym(col_name) == 6 & a == 3,
8, !!sym(col_name)))
其他替代方法包括使用 get
:
df %>% mutate(!!col_name := if_else(get(col_name) == 6 & a == 3,
8, get(col_name)))
或不使用任何 NSE .data
:
df %>% mutate(!!col_name := if_else(.data[[col_name]] == 6 & a == 3,
8, .data[[col_name]]))
使用基础:
df[ df[, col_name ] == 6 & df$a == 3, col_name ] <- 8
df
# a b
# 1 1 2
# 2 2 4
# 3 3 8
注意: 是的,我知道问题是关于 "整洁",这只是为了说明为什么一些简单的任务基础解决方案就像 good/better.