【问题标题】:R How to loop multiple calculations over each unique factors in a column of my data and append each calculation to a new column or tableR如何对我的数据列中的每个唯一因素循环多个计算并将每个计算附加到新列或表中
【发布时间】:2018-11-28 16:42:42
【问题描述】:

我有大量数据,我希望为我的数据集中的每家公司制作一份报告。报告有4列,前3列为固定文本,最后一列需要根据各公司数据计算。理想的输出是这样的:

Issue_code    Description   Issue   # of violations  
   ..            ..          ..           2
   ..            ..          ..           5
   ..            ..          ..           18  

数据中大约有 16 家独特的公司。因此,最后我将有 16 个这样的表,前 3 列相同,最后一列不同。

我的循环启动如下:

for (i in unique(data$company) {

  i1 <-  filter(company == i) %>%
         summarise_at("ID", funs(sum(is.na(.))))

  i2 <-  filter(company == i) %>%
         filter(Frequency > 5) %>%
         count()

  i3 <-  filter(company == i) %>%
         filter( Year %in% c(1998, 1996, 1997) %>%
         summarise_at("amount", funs(sum(is.na(.))))
}

而且我无法将这些计算分配(循环)到相应的表或列。我正在考虑列出 16 列“违规次数”并将每个计算分配给每个表,但我的 R 技能无法达到我的想法。任何帮助将不胜感激!

【问题讨论】:

    标签: r loops for-loop iteration purrr


    【解决方案1】:

    我们可以按公司分组,在summarise_at中使用多个列

    library(dplyr)
    data %>%
         group_by(company) %>%
          summarise_at(vars(ID,Frequency, Date), funs(sum(is.na(.)))
    

    如果我们有兴趣对列应用不同的功能,请使用map

    map2(c("ID", "Frequency", "Date"), listofFunctions, ~ 
                    data %>%
                        group_by(company) %>%
                        summarise_at(.x, funs(.y))
    

    【讨论】:

    • 抱歉,我没有指定并非所有计算都计算 NA,而且有些计算需要进一步过滤。我将在问题中编辑我的代码。谢谢阿克伦!
    猜你喜欢
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2020-03-19
    • 2019-03-03
    • 2019-09-05
    相关资源
    最近更新 更多