The base
R 解决方案ave()
:
within(df, BA_Larger <- ave(BasalArea, Plot, FUN = function(x) sapply(x, function(y) sum(x[x > y]))))
With a tidyverse
风格,你也可以使用map_int()
or map_dbl()
from purrr
.
library(dplyr)
library(purrr)
df %>%
group_by(Plot) %>%
mutate(BA_Larger = map_int(BasalArea, ~ sum(BasalArea[BasalArea > .]))) %>%
ungroup()
Output
# # A tibble: 8 x 4
# Plot Tree BasalArea BA_Larger
# <int> <int> <int> <int>
# 1 1 1 4 12
# 2 1 2 5 7
# 3 1 3 7 0
# 4 1 4 3 16
# 5 2 1 4 20
# 6 2 2 6 9
# 7 2 3 9 0
# 8 2 4 5 15
Data
df <- structure(list(Plot = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), Tree = c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L), BasalArea = c(4L, 5L, 7L, 3L, 4L,
6L, 9L, 5L)), class = "data.frame", row.names = c(NA, -8L))