首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有多因素条件的行和

具有多因素条件的行和
EN

Stack Overflow用户
提问于 2020-01-24 06:31:33
回答 2查看 55关注 0票数 0

我试图对具有不同条件的行求和,但我在这部分遇到了困难。

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

代码语言:javascript
复制
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)

我想要的是用相同类型的访问者计算来自相同花种的n(gr列),甚至在相关列( an )中有两个条目:例如,我想要的最终产品是一个表,给我一个表,其中有3种不同的os动物(蜜蜂、甲虫和蝙蝠)访问向日葵,66次昆虫访问(所有动物的总和标记为‘’昆虫‘’)和3次来自哺乳动物。

我不知道我是否恰当地表达了自己的意思,但我会感谢任何形式的帮助

EN

回答 2

Stack Overflow用户

发布于 2020-01-24 07:36:53

代码语言:javascript
复制
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))
票数 0
EN

Stack Overflow用户

发布于 2020-01-24 07:58:41

我相信@georgery right..being是tidyverse的粉丝,我更喜欢他的方法而不是@arkun。

以下是对他的解决方案的略微改进:

代码语言:javascript
复制
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)))

结果将是一个tibble

代码语言:javascript
复制
  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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59887997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档