【问题标题】:Row sums with multiple factor conditions具有多因子条件的行总和
【发布时间】:2020-05-10 06:46:33
【问题描述】:

我正在尝试对具有不同条件的行求和,但我陷入了这一部分。

这是我的数据库的类似示例:

fl<-c("rose", "sunflower", "rose", "sunflower", "lily", "sunflower", "rose", "sunflower")
an<-c("sunbird", "beetle", "beetle", "bee", "bee", "bee", "fly", "bat")
gr<-c("bird", "insect", "insect", "insect", "insect", "insect", "insect", "mammal")
n<-c(2, 3, 7, 15, 23, 48,11, 3)
df<-data.frame(fl, an, gr, n)

我想要的是用相同类型的访客(列 gr)计算来自相同花种的 n,即使在相关列 (an) 中有重复条目:例如,我想要的最终产品to have 是一张表格,上面有 3 种不同的 os 群动物(蜜蜂、甲虫和蝙蝠)访问了向日葵,昆虫访问了 66 次(所有标记为“昆虫”的动物的总和)和哺乳动物访问了 3 次

我不知道我是否正确地表达了自己,但我很感激任何形式的帮助

【问题讨论】:

  • 您需要rolluplibrary(data.table);setDT(df);rollup(df, j = sum(n), by = c("fl","an","gr")) 还是cube cube(df, j = sum(n), by = c("fl","an","gr"))

标签: r dataframe indexing


【解决方案1】:

我相信 @georgery 几乎是对的。作为 tidyverse 的粉丝,我更喜欢他的方法而不是 @arkun。

这是对他的解决方案的轻微改进:

library(dplyr)
fl<-c("rose", "sunflower", "rose", "sunflower", "lily", "sunflower", "rose", "sunflower")
an<-c("sunbird", "beetle", "beetle", "bee", "bee", "bee", "fly", "bat")
gr<-c("bird", "insect", "insect", "insect", "insect", "insect", "insect", "mammal")
n<-c(2, 3, 7, 15, 23, 48,11, 3)
df<-data.frame(fl, an, gr, n, stringsAsFactors = FALSE)

df %>% 
  group_by(fl, gr) %>%
  summarise(category = sum(n), typewithincategory=length(unique(an)))

结果将是一个小标题

  fl        gr     category typewithincategory
  <chr>     <chr>     <dbl>              <int>
1 lily      insect       23                  1
2 rose      bird          2                  1
3 rose      insect       18                  2
4 sunflower insect       66                  2
5 sunflower mammal        3                  1

【讨论】:

  • 你的函数对我来说有一点问题:在这个例子中,我有两个 ''bee'' 条目,并且函数计数了两次。在这种情况下,有没有我可以用来识别独特因素的论据?
  • @DaniloCarvalho 这很简单。 summarise 中的 length 参数现在查找 unique。查找更新。
【解决方案2】:
library(tidyverse)

fl<-c("rose", "sunflower", "rose", "sunflower", "lily", "sunflower", "rose", "sunflower")
an<-c("sunbird", "beetle", "beetle", "bee", "bee", "bee", "fly", "bat")
gr<-c("bird", "insect", "insect", "insect", "insect", "insect", "insect", "mammal")
n<-c(2, 3, 7, 15, 23, 48,11, 3)
df<-data.frame(fl, an, gr, n, stringsAsFactors = FALSE)

df %>%
    group_by(fl, an) %>%
    summarise(howMany = sum(n))

【讨论】:

  • 我真的很感谢你的帮助,它帮助了很多@georgery
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 2018-08-22
相关资源
最近更新 更多