gpt4 book ai didi

r - 如何在 R 中动态改变数据框中的列

转载 作者:行者123 更新时间:2023-12-02 02:35:49 26 4
gpt4 key购买 nike

我想改变定义为变量 (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)

最佳答案

使用基础:

df[ df[, col_name ] == 6 & df$a == 3, col_name ] <- 8

df
# a b
# 1 1 2
# 2 2 4
# 3 3 8

注意:是的,我知道问题是关于“整洁”的,这只是为了说明为什么对于一些简单的任务,基本解决方案同样好/更好。

关于r - 如何在 R 中动态改变数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64333369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com