使用dplyr从多列计算分位数

时间:2018-07-11 14:10:05

标签: r dplyr confidence-interval quantile

我有一个这样的数据框

set.seed(123)

对于向量,如果要生成均值以及上下95%CI,则可以执行以下操作:

 x <- rnorm(20)

quantile(x, probs = 0.500) # mean
quantile(x, probs = 0.025) # lower 
quantile(x, probs = 0.975) # upper bound

我有一个数据框

df <- data.frame(loc = rep(1:2, each = 4), 
                 year = rep(1980:1983, times = 2),
                 x1 = rnorm(8), x2 = rnorm(8), x3 = rnorm(8), x4 = rnorm(8), 
                 x5 = rnorm(8), x6 = rnorm(8), x7 = rnorm(8), x8 = rnorm(8))

对于每个位置和年份,我想使用x1到x8查找中位数,下限和上限。

df %>% group_by(loc, year) %>% 
dplyr::summarise(mean.x = quantile(x1, x2, x3, x4, x5, x6 , x7, x8, probs = 0.500),
                 lower.x = quantile(x1, x2, x3, x4, x5, x6 , x7, x8, probs = 0.025),
                 upper.x = quantile(x1, x2, x3, x4, x5, x6 , x7, x8, probs = 0.975))

但这给我所有人一个相同的答案。

# A tibble: 8 x 5
# Groups:   loc [?]
loc  year mean.x lower.x upper.x
<int> <int>  <dbl>   <dbl>   <dbl>
  1     1  1980 -1.07   -1.07   -1.07 
2     1  1981 -0.218  -0.218  -0.218
3     1  1982 -1.03   -1.03   -1.03 
4     1  1983 -0.729  -0.729  -0.729
5     2  1980 -0.625  -0.625  -0.625
6     2  1981 -1.69   -1.69   -1.69 
7     2  1982  0.838   0.838   0.838
8     2  1983  0.153   0.153   0.153

此外,除了通过x1,x2 ... x8引用列之外,还有什么方法可以通过索引之类的方式完成

3:ncol(df)

2 个答案:

答案 0 :(得分:2)

您可能需要先将宽数据转换为长数据:

require(dplyr)
require(tidyr)
df %>% gather(xvar, value, x1:x8) %>% 
group_by(loc, year) %>% 
summarise(mean.x = quantile(value, probs = 0.50),
          lower.x = quantile(value, probs = 0.025),
          upper.x = quantile(value, probs = 0.975))

您得到:

# A tibble: 8 x 5
# Groups:   loc [?]
    loc  year  mean.x lower.x upper.x
  <int> <int>   <dbl>   <dbl>   <dbl>
1     1  1980  0.152   -0.982   2.08 
2     1  1981 -0.478   -1.33    0.825
3     1  1982 -0.0415  -1.95    1.02 
4     1  1983  0.855   -0.180   1.43 
5     2  1980  0.658   -1.24    2.23 
6     2  1981  0.196   -0.782   0.827
7     2  1982 -0.629   -0.937   0.285
8     2  1983 -0.0737  -0.744   1.27 

答案 1 :(得分:1)

函数sh仅需要一个输入向量。

find

您正在向它提供8个输入向量,它将仅使用quantile,而忽略quantile(x1, x2, x3, x4, x5, x6 , x7, x8, probs = 0.5) x1

示例:

x2

要解决您的特定问题,请将x8放在x <- rnorm(20) y = rnorm(20) + 100 quantile(x, probs = 0.025) # lower # 2.5% # -1.633378 quantile(x, y, probs = 0.025) # y will be ignored. This yields same result as quantile(x, probs = 0.025). A warning explains this # 2.5% # -1.633378 # Warning message: # In if (na.rm) x <- x[!is.na(x)] else if (anyNA(x)) stop("missing values and NaN's not allowed if 'na.rm' is FALSE") : # the condition has length > 1 and only the first element will be used 内的x1中以形成向量:

x8

产量:

c()

顺便说一句,上限应该是0.975,你有错别字0.0975