r - 创建一个新行,其中包含 1 - R 数据框中的列值之和

标签 r dataframe matrix

我有一个不同样本中物种相对丰度 (%) 的多变量数据集。在这个数据框中我只有最丰富的物种,所以总数不是100%。

我的数据集看起来像这样,但有更多的物种和样本:

species = c("Species1","Species2","Species3","Species4","Species5","Species6")
Sample1 = c(0.6,7.9,7.1,2.7,4.5,6.4)
Sample2 = c(1.8,0.3,0.9,3.3,1.7,9.8)
Sample3 = c(9.2,1,8,2.1,8,2.2)
Sample4 = c(6.1,1.3,9,5.3,5.5,6.2)

df = data.frame(species, Sample1, Sample2, Sample3, Sample4)
df

   species Sample1 Sample2 Sample3 Sample4
1 Species1     0.6     1.8     9.2     6.1
2 Species2     7.9     0.3     1.0     1.3
3 Species3     7.1     0.9     8.0     9.0
4 Species4     2.7     3.3     2.1     5.3
5 Species5     4.5     1.7     8.0     5.5
6 Species6     6.4     9.8     2.2     6.2

但是我想制作一个堆积条形图,其中还有变量“其他”代表所有最稀有物种的覆盖百分比,计算方式为100 - 列总和

我想要的结果是这样的:

   species Sample1 Sample2 Sample3 Sample4
1 Species1     0.6     1.8     9.2     6.1
2 Species2     7.9     0.3     1.0     1.3
3 Species3     7.1     0.9     8.0     9.0
4 Species4     2.7     3.3     2.1     5.3
5 Species5     4.5     1.7     8.0     5.5
6 Species6     6.4     9.8     2.2     6.2
7   Others    70.8    82.2    69.5    66.6

我该怎么办?我已经搜索了几个小时但找不到解决方案。

最佳答案

要获取所需的数据,请使用summarize(across())

bind_rows(
  df,
  df %>% summarize(across(starts_with("Sample"),~100-sum(.x))) %>% 
    mutate(species="Others")
)

输出:

   species Sample1 Sample2 Sample3 Sample4
1 Species1     0.6     1.8     9.2     6.1
2 Species2     7.9     0.3     1.0     1.3
3 Species3     7.1     0.9     8.0     9.0
4 Species4     2.7     3.3     2.1     5.3
5 Species5     4.5     1.7     8.0     5.5
6 Species6     6.4     9.8     2.2     6.2
7   Others    70.8    82.2    69.5    66.6

此外,如果您想在简单的堆积条形图中绘制它,您可以使用以下命令继续管道:

... %>% pivot_longer(cols = -species, names_to="Sample",values_to = "Abundance") %>% 
  ggplot(aes(Sample,Abundance,fill=species)) + 
  geom_col() + 
  labs(fill="", y="Relative Abundance")+
  theme(legend.position = "bottom")

relative_abundance

关于r - 创建一个新行,其中包含 1 - R 数据框中的列值之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72194688/

相关文章:

python - 找出每列是行最小值的频率

java - Android 版 OpenCV 中的基本矩阵乘法

r - 使用 dplyr 将行添加到数据框中

python-3.x - 如何使用 python 对数据帧之间的降序进行排序

python - pandas 将值列添加到日期时间

opengl - 视野 + 纵横比 + 投影矩阵的 View 矩阵(HMD OST 校准)

javascript - 将矩阵插入数组

r - getSymbols 仍然可以与 oanda 一起使用吗?

r - 如何定义S4方法来取对象的反面?

从 R 中的箱线图框架中删除顶部和右侧边框