【问题标题】:R dplyr: summarise_each from an external lookup table?R dplyr:来自外部查找表的 summarise_each?
【发布时间】:2016-06-27 22:21:50
【问题描述】:

如何使用dplyr 解决以下玩具问题:

取一个数据框,其中每行至少包含两个用空格分隔的鸢尾花:

mySpecies <- data.frame(
  Species=c("lazica uniflora setosa", 
        "virginica setosa uniflora loczyi",
        "versicolor virginica"))

我想在“mySpecies”中添加 2 列,其中每行包含 Sepal.Length 和 Sepal.Width 的平均值 仅适用于单独查找表中可用的那些物种:鸢尾花数据集:unique(iris$Species)

此示例的输出应该是 mySpecies 数据框,其中包含附加的“Sepal.Length.mean”和“Sepal.Width.mean”列,其中包含出现在 iris$Species 中的每个物种的这些变量的平均值。

所以第一行将只包含“setosa”的 Sepal.Length 和 Sepal.Width,因为其他物种名称不会出现在 iris 中。然而,第二行将包含跨 'virginica' 和 'setosa' 的 Sepal.Length 和 Sepal.Width 的平均值,因为它们都出现在查找表中(即iris)。

请注意,这是一个玩具示例,但我的实际数据框非常大。

【问题讨论】:

  • 那么您的示例所需的输出是什么?
  • 不清楚你想要怎样的输出
  • 你是说iris %&gt;% group_by(Species) %&gt;% summarise_each(funs(mean), Sepal.Length:Sepal.Width) %&gt;% bind_cols(., mySpecies)
  • 我已经详细说明了所需的输出

标签: r dplyr


【解决方案1】:

给你。首先,将您的字符串拆分为单个物种;然后对于每个组:过滤匹配的行,并计算平均值。

mySpecies %>%
    group_by(Species) %>%
    do({
        spec <- strsplit(as.character(.$Species), " ", fixed=TRUE)[[1]]
        filter(iris, Species %in% spec) %>%
            summarise_each(funs(mean), Sepal.Length, Sepal.Width)
    })

【讨论】:

    【解决方案2】:
    library(dplyr)
    
    mySpecies= c("setosa", "loczyi", "virginica")
    
    filter(iris, Species %in% mySpecies) %>%
        group_by(iris, Species) %>% 
        summarise(mean_width = mean(Sepal.Width),
                  mean_length = mean(Sepal.Length))
    

    【讨论】:

      猜你喜欢
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多