ult*_*ron 4 statistics r dplyr
我有像多列一个巨大的数据集x1,x2,x3...... x25,y1,y2,y3...... y50,z1,z2...... z10等,这些看起来是这样的:
x1 x2 x3 x4 y1 y2 y3
1 2 1 2 1 1 2
2 1 1 1 3 1 1
1 2 2 1 1 2 1
Run Code Online (Sandbox Code Playgroud)
我想要的是:
x_mean x_min x_max x_mad y_mean y_min y_max y_mad
1.5 1 2 0.74 2 1 2 0
1.25 1 2 0 2 1 2 0
1.5 1 2 0.74 2 1 2 0
Run Code Online (Sandbox Code Playgroud)
基本上,我需要计算min,max,mad(中位数绝对偏差),和mean
> x_mean = (x1+x2+x3+x4)/4 = (1+2+1+2)/4
Run Code Online (Sandbox Code Playgroud)
和其他行和其他统计数据类似.我如何在R中执行此操作,最好是在dplyr中?
通常,您可以使用summariselike 的范围变体summarise_all,在其funs辅助函数中可以接受任意数量的汇总函数.在您的情况下,您应首先重塑为长形式,以便使您的数据整洁(此处将观察从列移动到行),从而使您的分析更简单:
library(tidyverse)
df <- read.table(text = 'x1 x2 x3 x4 y1 y2 y3
1 2 1 2 1 1 2
2 1 1 1 3 1 1
1 2 2 1 1 2 1', head = TRUE)
df_tidy <- df %>%
mutate(row = row_number()) %>% # keep position info
gather(var, val, -row) %>% # reshape to long
mutate(var = sub('\\d', '', var)) # extract letters from former colnames
df_summary <- df_tidy %>%
group_by(var, row) %>% # group by variable and original row
summarise_all(funs(min, max, mad)) # summarize with various functions
df_summary
#> # A tibble: 6 x 5
#> # Groups: var [?]
#> var row min max mad
#> <chr> <int> <dbl> <dbl> <dbl>
#> 1 x 1 1 2 0.7413
#> 2 x 2 1 2 0.0000
#> 3 x 3 1 2 0.7413
#> 4 y 1 1 2 0.0000
#> 5 y 2 1 3 0.0000
#> 6 y 3 1 2 0.0000
Run Code Online (Sandbox Code Playgroud)
如果你愿意的话,你可以将它重新塑造成宽边,但是出于演示目的,我会建议反对它.