[英]How to get the results of a mean and standard deviation to the same data frame by creating extra columns (mean and standard deviation) in R
[英]Plotting mean and standard deviation for every numeric value in data frame in R
我想用平均值绘制每个数字列作为条形,标准偏差是一条穿过条形的线。 如何为iris
数据集执行此操作?
我正在尝试转换我的数据集以使其易于在 ggplot2 中绘图。
我试过的
iris %>%
dplyr::select_if(is.numeric) %>%
dplyr::summarise(avg_sepal_length = mean(Sepal.Length),
avg_sepal_width = mean(Sepal.Width),
avg_petal_length = mean(Petal.Length),
avg_petal_width = mean(Petal.Width),
sd_sepal_length = sd(Sepal.Length),
sd_sepal_width = sd(Sepal.Width),
sd_petal_length = sd(Petal.Length),
sd_petal_width = sd(Petal.Width))
我想旋转成两列,所以数据框看起来像这样:
stat mean sd
sepal_length 5.843333 0.8280661
sepal_width 3.057333 0.4358663
petal_length 3.758 1.765298
pedal_width 1.199333 0.7622377
然后将上限和下限绘制为 sd 和 the 的一条线。 意思是 ggplot 中的条形图
您的输出格式不是ggplot2
的最佳格式,它更喜欢它:
library(tidyr); library(dplyr)
iris %>%
summarise(
across(
where(is.double),
list(mean = mean, sd = sd)
)
) |>
pivot_longer(
everything(),
names_sep = "_",
names_to = c("feature", "stat")
)
# A tibble: 8 x 3
# feature stat value
# <chr> <chr> <dbl>
# 1 Sepal.Length mean 5.84
# 2 Sepal.Length sd 0.828
# 3 Sepal.Width mean 3.06
# 4 Sepal.Width sd 0.436
# 5 Petal.Length mean 3.76
# 6 Petal.Length sd 1.77
# 7 Petal.Width mean 1.20
# 8 Petal.Width sd 0.762
由于您熟悉iris
数据集,因此值得查看大量使用它across
文档。
要获得您的格式,您可以将以下内容添加到管道中:
|>
pivot_wider(names_from = "stat")
# # A tibble: 4 x 3
# feature mean sd
# <chr> <dbl> <dbl>
# 1 Sepal.Length 5.84 0.828
# 2 Sepal.Width 3.06 0.436
# 3 Petal.Length 3.76 1.77
# 4 Petal.Width 1.20 0.762
为了达到您想要的结果,您可以首先使用dplyr::across
简化您的代码。 之后,您可以通过pivot_longer
转换为 long ,从而使用.value
允许将mean
s 和sd
s 放在它们自己的列中。 最后,您可以将绘图作为geom_col
和geom_pointrange
的组合:
library(dplyr)
library(tidyr)
library(ggplot2)
iris_sum <- iris %>%
summarise(across(where(is.numeric), .fns = list(avg = mean, sd = sd), .names = "{.fn}_{.col}")) |>
pivot_longer(everything(), names_to = c(".value", "name"), names_sep = "_") |>
mutate(name = gsub("\\.", '_', tolower(name)))
iris_sum
#> # A tibble: 4 × 3
#> name avg sd
#> <chr> <dbl> <dbl>
#> 1 sepal_length 5.84 0.828
#> 2 sepal_width 3.06 0.436
#> 3 petal_length 3.76 1.77
#> 4 petal_width 1.20 0.762
ggplot(iris_sum, aes(name, avg)) +
geom_col() +
geom_pointrange(aes(ymin = avg - sd, ymax = avg + sd))
请注意,您实际上不需要预处理 df 来计算汇总值,您可以直接使用 ggplot2 的stat_summary
:
library(ggplot2)
ggplot(stack(iris), aes(x = ind, y = values)) +
stat_summary(geom = "bar", fun = mean) +
stat_summary(
fun = mean,
fun.min = function(x) mean(x) - sd(x),
fun.max = function(x) mean(x) + sd(x))
在这里,我使用了 base R 的简单stack
函数来制作虹膜数据集的长版本; 您可以使用您喜欢的任何库(特别是如果您想包含其他操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.