我们可以通过列名的子字符串拆分数据集,遍历list并获取rowSums并使用barplot
out <- sapply(split.default(df1, sub("\\d+$", "", names(df1))),
rowSums, na.rm = TRUE)
barplot(out)
如果有更多行并且想要绘制,请使用tidyverse,我们可以通过使用列名中的模式,即捕获不带数字的列名的子字符串,使用pivot_longer 重塑为“长”格式结束。这将创建 4 列。然后,我们使用summarise 和across 来获取每列的sum 并返回一个条形图 - geom_col
library(dplyr)
library(tidyr)
library(ggplot2)
df2 %>%
pivot_longer(cols = everything(), names_to = ".value",
names_pattern = "(.*)\\d+$") %>%
summarise(across(everything(), sum, na.rm = TRUE)) %>%
pivot_longer(cols = everything()) %>%
ggplot(aes(x = name, y = value, fill = name)) +
geom_col()
-输出
如果我们对数据的传播感兴趣,箱线图可以提供帮助。在这里,我们不用summarise,而是用geom_boxplot代替geom_col
df2 %>%
pivot_longer(cols = everything(), names_to = ".value",
names_pattern = "(.*)\\d+$") %>%
pivot_longer(cols = everything()) %>%
ggplot(aes(x = name, y = value, fill = name)) +
geom_boxplot()
数据
df1 <- structure(list(D1A1 = 10L, D1A2 = 12L, D1A3 = 15L, D1B1 = 40L,
D1B2 = 39L, D1B3 = 27L, D2A1 = 11L, D2A2 = 13L, D2A3 = 14L,
D2B1 = 33L, D2B2 = 31L, D2B3 = 32L), class = "data.frame", row.names = c(NA,
-1L))
df2 <- structure(list(D1A1 = c(10L, 15L), D1A2 = c(12L, 23L), D1A3 = 15:14,
D1B1 = c(40L, 23L), D1B2 = c(39L, 14L), D1B3 = c(27L, 22L
), D2A1 = 11:10, D2A2 = c(13L, 15L), D2A3 = c(14L, 17L),
D2B1 = c(33L, 35L), D2B2 = c(31L, 35L), D2B3 = c(32L, 32L
)), class = "data.frame", row.names = c(NA, -2L))