我首先在正态分布中模拟了500个大小为55的样本。
samples <- replicate(500, rnorm(55,mean=50, sd=10), simplify = FALSE)
1)对于每个样本,我想要平均值,中位数,范围和第三个四分位数。然后我需要将它们一起存储在数据框中。
这就是我所拥有的。我不确定范围或分位数。我尝试了lapply和lapply但不确定它们是如何工作的。
stats <- data.frame(
means = map_dbl(samples,mean),
medians = map_dbl(samples,median),
sd= map_dbl(samples,sd),
range= map_int(samples, max-min),
third_quantile=sapply(samples,quantile,type=3)
)
2)然后绘制平均值的采样分布(直方图)。我尝试绘制,但我不知道如何得到平均值
stats <- gather(stats, key = "Trials", value = "Mean")
ggplot(stats,aes(x=Trials))+geom_histogram()
3)然后我想在单个绘图窗口的(三个单独的图形)中绘制其他三个统计数据。
我知道我需要使用像gather和facet_wrap这样的东西,但我不知道该怎么做。
你快到了。所需要的只是在有错误的地方定义匿名函数。
library(tidyverse)
set.seed(1234) # Make the results reproducible
samples <- replicate(500, rnorm(55,mean=50, sd=10), simplify = FALSE)
str(samples)
stats <- data.frame(
means = map_dbl(samples, mean),
medians = map_dbl(samples, median),
sd = map_dbl(samples, sd),
range = map_dbl(samples, function(x) diff(range(x))),
third_quantile = map_dbl(samples, function(x) quantile(x, probs = 3/4, type = 3))
)
str(stats)
#'data.frame': 500 obs. of 5 variables:
# $ means : num 49.8 51.5 52.2 50.2 51.6 ...
# $ medians : num 51.5 51.7 51 51.1 50.5 ...
# $ sd : num 9.55 7.81 11.43 8.97 10.75 ...
# $ range : num 38.5 37.2 54 36.7 60.2 ...
# $ third_quantile: num 57.7 56.2 58.8 55.6 57 ...
您正在使用的map_dbl
函数绝对不错,但如果您最终想要获取数据框,那么您可能更容易将列表转换为数据框,然后利用一些dplyr
功能。
我首先在列表上进行映射,创建tibbles,并使用添加的ID将它绑定在一起。转换会创建样本值的列value
。 summarise_at
允许您获取函数列表 - 在列表中提供名称设置结果数据框中的名称。您可以使用purrr
的~.
表示法在需要的地方内联定义这些函数。减少你必须使用map_dbl
等的次数。
library(tidyverse)
stats <- samples %>%
map_dfr(as_tibble, .id = "sample") %>%
group_by(sample) %>%
summarise_at(vars(value),
.funs = list(mean = mean, median = median, sd = sd,
range = ~(max(.) - min(.)),
third_quartile = ~quantile(., probs = 0.75)))
head(stats)
#> # A tibble: 6 x 6
#> sample mean median sd range third_quartile
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 45.0 44.4 8.71 47.6 48.6
#> 2 10 51.0 52.0 9.55 49.3 56.2
#> 3 100 51.6 52.2 10.4 60.7 58.1
#> 4 101 51.6 51.1 9.92 37.6 57.2
#> 5 102 49.1 48.2 9.65 39.8 57.0
#> 6 103 52.2 51.3 10.1 47.4 58.5
接下来,在您的代码中,您可以使用数据 - 这通常是人们在SO上需要的解决方案 - 但如果您只是尝试显示平均列,则可以按原样使用它。
gather