管理一列中的重复条目,同时在 r 中保持其他列不变
Managing duplicate entries in one column while keeping other columns intact in r
我有多个站点的物种计数数据,包括站点、年、月和日的信息。在此数据中,对于几个物种,在某些日子有多个条目。例如,2016 年 1 月 3 日,对于物种 A1,有两个条目,即 10 和 20。第一步,我想取这一天的最大值,即 20。在第二步,如果有多个条目每个站点每月抽样一天,然后我想取每月的平均值。例子如下
species site year month day total
A1 GG 2016 1 3 10
A1 GG 2016 1 3 20
A1 GG 2016 1 4 22
A2 GG 2016 1 5 32
A2 GG 2016 1 6 34
A3 GG 2016 1 9 23
应该看起来像这样
species site year month day total
A1 GG 2016 1 3.5 21
A2 GG 2016 1 5.5 33
A3 GG 2016 1 9 23
我们按前五列分组,即'species'、'site'、'year'、'month'、'day'、summarise
得到'total' 的 max
,然后在没有 'day' 的情况下进行分组,得到 'day' 和 'total'
的 mean
library(dplyr)
df1 %>%
group_by_at(names(.)[1:5]) %>%
summarise(total = max(total)) %>%
group_by_at(names(.)[1:4]) %>%
summarise_all(mean)
# A tibble: 3 x 6
# Groups: species, site, year [?]
# species site year month day total
# <chr> <chr> <int> <int> <dbl> <dbl>
#1 A1 GG 2016 1 3.50 21.0
#2 A2 GG 2016 1 5.50 33.0
#3 A3 GG 2016 1 9.00 23.0
作为参考,这里是使用data.table
的解决方案
> library(data.table)
> dt <- fread("
species site year month day total
A1 GG 2016 1 3 10
A1 GG 2016 1 3 20
A1 GG 2016 1 4 22
A2 GG 2016 1 5 32
A2 GG 2016 1 6 34
A3 GG 2016 1 9 23
")
> cols_with_day <- c('species', 'site', 'year', 'month', 'day')
> cols_without_day <- c('species', 'site', 'year', 'month')
> result <- dt[, .(total = max(total)), by = cols_with_day
][, .(day = mean(day), total = mean(total)), by = cols_without_day]
> result
species site year month day total
1: A1 GG 2016 1 3.5 21
2: A2 GG 2016 1 5.5 33
3: A3 GG 2016 1 9.0 23
我有多个站点的物种计数数据,包括站点、年、月和日的信息。在此数据中,对于几个物种,在某些日子有多个条目。例如,2016 年 1 月 3 日,对于物种 A1,有两个条目,即 10 和 20。第一步,我想取这一天的最大值,即 20。在第二步,如果有多个条目每个站点每月抽样一天,然后我想取每月的平均值。例子如下
species site year month day total
A1 GG 2016 1 3 10
A1 GG 2016 1 3 20
A1 GG 2016 1 4 22
A2 GG 2016 1 5 32
A2 GG 2016 1 6 34
A3 GG 2016 1 9 23
应该看起来像这样
species site year month day total
A1 GG 2016 1 3.5 21
A2 GG 2016 1 5.5 33
A3 GG 2016 1 9 23
我们按前五列分组,即'species'、'site'、'year'、'month'、'day'、summarise
得到'total' 的 max
,然后在没有 'day' 的情况下进行分组,得到 'day' 和 'total'
mean
library(dplyr)
df1 %>%
group_by_at(names(.)[1:5]) %>%
summarise(total = max(total)) %>%
group_by_at(names(.)[1:4]) %>%
summarise_all(mean)
# A tibble: 3 x 6
# Groups: species, site, year [?]
# species site year month day total
# <chr> <chr> <int> <int> <dbl> <dbl>
#1 A1 GG 2016 1 3.50 21.0
#2 A2 GG 2016 1 5.50 33.0
#3 A3 GG 2016 1 9.00 23.0
作为参考,这里是使用data.table
> library(data.table)
> dt <- fread("
species site year month day total
A1 GG 2016 1 3 10
A1 GG 2016 1 3 20
A1 GG 2016 1 4 22
A2 GG 2016 1 5 32
A2 GG 2016 1 6 34
A3 GG 2016 1 9 23
")
> cols_with_day <- c('species', 'site', 'year', 'month', 'day')
> cols_without_day <- c('species', 'site', 'year', 'month')
> result <- dt[, .(total = max(total)), by = cols_with_day
][, .(day = mean(day), total = mean(total)), by = cols_without_day]
> result
species site year month day total
1: A1 GG 2016 1 3.5 21
2: A2 GG 2016 1 5.5 33
3: A3 GG 2016 1 9.0 23