如何根据R中其他列的特定条件对一列的值求和?

3phpmpom  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(249)

我有一个数据集,看起来像这样:

df <- data.frame(plot = c("A","A","A","A","A","B","B","B","B","B","C","C","C","C","C"),
                 species = c("Fagus","Fagus","Quercus","Picea", "Abies","Fagus","Fagus","Quercus","Picea", "Abies","Fagus","Fagus","Quercus","Picea", "Abies"),
                 value =  sample(100, size = 15, replace = TRUE)) 

head(df)
  plot species value
1    A   Fagus    53
2    A   Fagus    48
3    A Quercus     5
4    A   Picea    25
5    A   Abies    12
6    B   Fagus    12

现在,我想创建一个新的 Dataframe ,其中包含share.conifersshare.broadleaves的每个plot值,方法是将values与适用于species的条件相加。我考虑过使用case_when,但不确定如何编写语法:

df1 <- df %>% share.broadleaves = case_when(plot = plot & species = "Fagus" or species = "Quercus" ~ FUN="sum")

df1 <- df %>% share.conifers = case_when(plot = plot & species = "Abies" or species = "Picea" ~ FUN="sum")

我知道这不对,但我想要这样的。

gcuhipw9

gcuhipw91#

使用dplyr/tidyr
首先构造组,进行计算,然后展开成列。

library(dplyr)
library(tidyr)

df |>
  mutate(type = case_when(species %in% c("Fagus", "Quercus") ~ "broadleaves",
                          species %in% c("Abies", "Picea") ~ "conifers")) |>
  group_by(plot, type) |>
  summarise(share = sum(value)) |>
  ungroup() |>
  pivot_wider(values_from = "share", names_from = "type", names_prefix = "share.")

输出量:

# A tibble: 3 × 3
  plot  share.broadleaves share.conifers
  <chr>             <int>          <int>
1 A                   159             77
2 B                    53             42
3 C                   204             63

我不确定你是想求和还是想得到份额,但代码可以很容易地适应你的任何目标。

li9yvcax

li9yvcax2#

一种方法是通过plotspecies进行总结:

library(dplyr)
df |>
  group_by(plot, species) |>
  summarize(share = sum(value))

如果你真的想得到每一地块的特定物种的份额,你也可以这样做:

df |>
  group_by(plot) |>
  summarize(share_certain_species = sum(value[species %in% c("Fagus", "Quercus")]) / sum(value))

其给出:

# A tibble: 3 × 2
  plot  share_certain_species
  <chr>                 <dbl>
1 A                     0.546
2 B                     0.583
3 C                     0.480

相关问题