【问题标题】:How to use a variable name in a formula instead of the column itself如何在公式中使用变量名而不是列本身
【发布时间】:2022-10-17 23:21:20
【问题描述】:

我有数据,我想使用summary_by功能(从多比包裹)。我不能在summary_by公式,但我之前创建的变量。
以下是我想要达到的结果:

library(data.table)
library(doBy)

mtcars = data.table(mtcars)

doBy::summary_by(data = mtcars, mpg ~ gear + am, FUN = "mean")

输出:

gear  am   mpg."mean"
3     0    16.10667
4     0    21.05000
4     1    26.27500
5     1    21.38000

这是我想做的:

library(data.table)
library(doBy)

mtcars = data.table(mtcars)

variable1 = "gear" # which is a column name of mtcars
variable2 = "am" # which is a column name of mtcars
variable3 = "mpg" # which is a column name of mtcars

doBy::summary_by(data = mtcars, variable3 ~ variable1 + variable2 , FUN = "mean")

我尝试了这些功能得到,分配,评估,管理但我没有找到解决方案。

【问题讨论】:

  • 该函数实际上已经存在于基础 R 中。aggregate(mpg ~ gear + am, mtcars, mean)

标签: r variables data.table formula


【解决方案1】:

只需提供一个字符串而不是依赖于非标准评估的公式。

library(data.table)
library(doBy)

mtcars = data.table(mtcars)

variable1 = "gear" # which is a column name of mtcars
variable2 = "am" # which is a column name of mtcars
variable3 = "mpg" # which is a column name of mtcars

doBy::summary_by(data = mtcars, 
                 # alternatively, use paste() oder glue()
                 sprintf("%s ~ %s + %s", variable3, variable1, variable2) , 
                 FUN = "mean")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2019-10-26
    • 2017-02-26
    • 2013-10-18
    • 1970-01-01
    • 2020-10-16
    相关资源
    最近更新 更多