我试图对具有不同条件的行求和,但我在这部分遇到了困难。
这是我的数据库的一个类似示例:
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次来自哺乳动物。
我不知道我是否恰当地表达了自己的意思,但我会感谢任何形式的帮助
发布于 2020-01-24 07:36:53
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))发布于 2020-01-24 07:58:41
我相信@georgery right..being是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)))结果将是一个tibble
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 1https://stackoverflow.com/questions/59887997
复制相似问题