После summarise
нам нужно ungroup
library(tidyverse)
df %>%
mutate(Abundance = rowSums(.[4:ncol(.)])) %>%
group_by(Site, Time) %>%
summarise_all(sum) %>%
ungroup %>%
mutate(Richness = apply(.[4:(ncol(.)-1)] > 0, 1, sum)) %>%
#or
#mutate(Richness = rowSums(.[4:(ncol(.)-1)] > 0)) %>%
select(Site, Time, Abundance, Richness)
# A tibble: 4 x 4
# Site Time Abundance Richness
# <chr> <chr> <dbl> <int>
#1 Home A 7 2
#2 Home B 7 2
#3 Work A 4 3
#4 Work B 4 3
Это также можно записать, выполнив сначала group_by
sum
, а затем transmute
df %>%
group_by(Site, Time) %>%
summarise_at(vars(matches("Species")), sum) %>%
ungroup %>%
transmute(Site, Time, Abundance = rowSums(.[3:ncol(.)]),
Richness = rowSums(.[3:ncol(.)] > 0))
Или другой вариант sum
с map
df %>%
group_by(Site, Time) %>%
summarise_at(vars(matches("Species")), sum) %>%
group_by(Time, add = TRUE) %>%
nest %>%
mutate(data = map(data, ~
tibble(Richness = sum(.x > 0),
Abundance = sum(.x)))) %>%
unnest
data
df <- structure(list(Site = c("Home", "Home", "Work", "Work", "Home",
"Home", "Work", "Work"), Time = c("A", "A", "A", "A", "B", "B",
"B", "B"), Sample = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), Species1 = c(1L,
0L, 0L, 1L, 1L, 0L, 0L, 1L), Species2 = c(0L, 0L, 1L, 0L, 0L,
0L, 1L, 0L), Species3 = c(4L, 2L, 1L, 1L, 4L, 2L, 1L, 1L)),
class = "data.frame", row.names = c(NA,
-8L))