我有一行数据框:
read.table(text = " V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
BACC 0.6203474 0.4466501 0.4820099 0.7003722 0.4851117 0.5173697 0.6073201 0.5911911 0.3759305 0.4627792")
每个列都是重复进行的相同计算(随机样本更改,因此平衡精度值会发生变化)。我想生成一个图表,显示带有误差条的迭代平均值(标准偏差)。因此,例如,在x = 1迭代时,它仅绘制列V1中给出的点。对于第二列,它平均第一列和第二列并计算std。开发。并绘制这个。对于第三列,它平均为第一列,第二列和第三列,并且一直相同,直到它最终平均所有并计算所有的标准偏差。
如何制作这个情节?或者包含每个迭代均值/标准差的数据框?我的真实数据有1000列(而不是10列)所以我想要一些可以扩展到尽可能大的数据集的东西。另外,如果我只想每5次迭代计算平均值/标准差,那该怎么办呢?
如果你能帮助我,我真的很感激。
谢谢!
答案 0 :(得分:0)
您可以使用一些tidyverse
个包和TTR
由于ggplot2
喜欢长格式的整洁数据,因此此解决方案使用gather
将所有测量列放入行中。这也使得更容易执行运行平均值并运行数据的标准偏差。
library(tidyverse) #for dplyr, tidyr, ggplot2
library(TTR) # for runMean and runSD
df <- read.table(text = " V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
BACC 0.6203474 0.4466501 0.4820099 0.7003722 0.4851117 0.5173697 0.6073201 0.5911911 0.3759305 0.4627792")
plot_data <- df %>%
gather(measurement, value) %>%
mutate(cum_mean = ifelse(value == first(value), value, runMean(value, 1, cumulative = TRUE)),
cum_sd = runSD(value, 1, cumulative = TRUE))
ggplot(plot_data, aes(x = measurement, y = cum_mean)) +
geom_col() +
geom_errorbar(aes(ymin = cum_mean - cum_sd, ymax = cum_mean + cum_sd), size = 0.2)
如果要在一系列行上执行此操作,例如每隔5行,您可以使用slice
实现此操作,并将序列包含在数据框中的行数上。
plot_data <- df %>%
gather(measurement, value) %>%
slice(seq(1, nrow(.), 5)) %>%
mutate(cum_mean = ifelse(value == first(value), value, runMean(value, 1, cumulative = TRUE)),
cum_sd = runSD(value, 1, cumulative = TRUE))