【问题标题】:Take function from dataframe从数据框中获取功能
【发布时间】:2021-05-27 11:45:06
【问题描述】:

我需要根据数据框中定义的输入执行计算。请参阅下面的数据框RefDf。它有 3 列 - 列名、计算、新变量名。当Calculation列包含计数时,我们应该使用n_distinct( )函数。

RefDf <- read.table(text = "Variables   Calculation NewVariable
Sepal.Length    sum Sepal.Length2
Petal.Length    count   Petal.LengthNew
", header = T)

手动方法 - 需要通过 RefDf 中的输入实现自动化。 Species 在分组时保持不变。

library(dplyr)
    iris %>% group_by_at("Species") %>% 
      summarise(Sepal.Length2 = sum(Sepal.Length,na.rm = T),
                Petal.LengthNew = n_distinct(Petal.Length, na.rm = T)
                )

我正在寻找基于 dplyr 或 base R 的解决方案

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    这是data.table 包的解决方案

    library(data.table)
    library(dplyr)
    
    # using data.table
    dt <- as.data.table(RefDf)
    dt[Calculation == "count", Calculation := "n_distinct"]
    # function for doing grouping calculation
    inner.fun <- function(calc, data, column, group="Species"){
      print(column)
      data.dt <- as.data.table(data)
      data.dt[, .(as.numeric(get(calc)(get(column)))), by=group][]
    }
    out <- dt[, inner.fun(calc=Calculation, data=iris, column=Variables), by=NewVariable]
    
    # reshape from wide to long
    out2 <- dcast(data=out, Species ~ NewVariable, value.var="V1")
    
    # convert to data.frame
    out_df <- as.data.frame(out2)
    out_df
             Species Petal.LengthNew Sepal.Length2
    1     setosa               9         250.3
    2 versicolor              19         296.8
    3  virginica              20         329.4
    

    【讨论】:

    • 谢谢。非常感激。我正在寻找基于 dplyr 或 base R 的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2013-11-23
    • 2021-12-19
    • 2019-07-03
    • 2016-02-24
    • 2021-06-11
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多