在R中的数据框中按因子水平添加比例列

gudnpqoy  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(73)

我有一个数据框,其中有一个“站点”列、一个“物种”列、一个“计数”列,加上其他列,我需要创建另一个使用“计数”数据按“物种”比例的列。

site <- c(rep("site1",3), rep("site2",4), rep("site3",2))
    species <- c("sp1","sp2","sp3","sp1","sp2","sp3","sp4","sp2","sp4")
    counts <- c(4,10,22,1,13,23,4,3,1)
    data <- cbind(site,species,counts)
   site species counts   ...
1 site1     sp1      4
2 site1     sp2     10
3 site1     sp3     22
4 site2     sp1      1
5 site2     sp2     13
6 site2     sp3     23
7 site2     sp4      4
8 site3     sp2      3
9 site3     sp4      1

字符串
我想要的数据框应该有和添加的列,按“物种”比例,像这样:

site species counts proportions_by_species   ...
1 site1     sp1      4                   0.80
2 site1     sp2     10                   0.38
3 site1     sp3     22                   0.49
4 site2     sp1      1                   0.20
5 site2     sp2     13                   0.50
6 site2     sp3     23                   0.51
7 site2     sp4      4                   0.80
8 site3     sp2      3                   0.11
9 site3     sp4      1                   0.20

nwnhqdif

nwnhqdif1#

library(dplyr)

site <- c(rep("site1",3), rep("site2",4), rep("site3",2))
species <- c("sp1","sp2","sp3","sp1","sp2","sp3","sp4","sp2","sp4")
counts <- c(4,10,22,1,13,23,4,3,1)
data <- data.frame(site,species,counts)

data <- data |> 
  group_by(species) |> 
  mutate(proportions_by_species = prop.table(counts))

字符串
或者

data <- data |> 
  group_by(species) |> 
  mutate(proportions_by_species = counts/sum(counts))

相关问题