如何使用 R 中的算术表达式改变数据集



我想使用 R 中的算术表达式动态改变数据集。 我尝试跟随但没有成功。感谢一些帮助。

newCol <- 'newCol=gear+wt'
mutate(mtcars,!!newCol) ## This inserted a column newCol=gear+wt
mutate(mtcars,!!sym(newCol)) ## THis gives an error 

'mutate_impl(.data, dots( 中的错误:找不到绑定:newCol=gear+wt。

这是对dplyr的非标准评估问题。

先引用您的表达式,然后取消引用。

newCol <- quo(gear + wt)
dplyr::mutate(mtcars, !! newCol)

这个在这里非常有帮助:https://dplyr.tidyverse.org/articles/programming.html

值得一读,这是很棒的:)

输入函数参数时不使用 <-。 在dplyr中,mutate 是一个允许您基于任何计算创建新列的函数。下面是一个示例:

library(dplyr)
dataset <- mtcars
dataset %>% mutate(newCol = gear+wt) 

这里不需要sym。 希望这就是你要找的。

library(dplyr)
newCol <- eval(parse(text='gear+wt'),list2env(mtcars))
mutate(mtcars, newCol = newCol)

或者,使用碱基 R 而不是 alterate:

mtcars$newCol <- eval(parse(text='gear+wt'),list2env(mtcars))
mtcars

最新更新