【问题标题】:Calculating percentiles across certain rows in a data frame in r计算r中数据框中某些行的百分位数
【发布时间】:2019-02-28 00:31:32
【问题描述】:

我的数据包含一年中每一天的温度测量值以及按村庄 ID 进行分析所需的其他变量。我想创建一个新变量来计算每个村庄所有 365 次温度测量的 95 个百分位阈值。

我的数据是宽格式的,如下所示:

    villageID temp1 temp2 temp3.... temp365 otherVars
1         1    70    86    98        79         x
2         2    73    89    99        86         x
3         3    71    82    96        75         x
4         4    78    79    94        81         x
5         5    90    91    89        85         x

我想创建这个 95% 阈值变量来计算阈值(或温度测量值),该阈值指示第 95 个百分位数从什么温度开始。我想在所有温度测量列[2:366] 中执行此操作,并保持所有其他变量相同。

像这样:

  villageID temp1 temp2 temp3 .....temp365 otherVars 95per
1         1    70    86    98        79         x      81
2         2    73    89    99        86         x      90
3         3    71    82    96        75         x      86
4         4    78    79    94        81         x      82
5         5    90    91    89        85         x      99

【问题讨论】:

  • 您不会选择使用95per,因为那时您需要始终引用或反引号该列名。也许temp.95per,我想你的意思是说所有行,但只说某些列?

标签: r rows quantile


【解决方案1】:

虽然我认为您应该将数据保留为长格式,但这里有一些代码可以计算它并将其放回您拥有的宽格式中。只是知道,这通常不是处理事情的最佳方式,尤其是如果您想稍后绘制数据:

library(tidyverse)

dat <- tribble(~"villageID", ~"temp1", ~"temp2", ~"temp3", ~"temp365", 
             1,    70,    86,    98,        79, 
             2,    73,    89,    99,        86, 
             3,    71,    82,    96,        75, 
             4,    78,    79,    94,        81, 
             5,    90,    91,    89,        85) 

dat %>% 
  gather(key = "day", value = "temp", -villageID) %>% 
  group_by(villageID) %>% 
  mutate(perc_95 = quantile(temp, probs = .95)) %>% 
  spread(day, temp)
#> # A tibble: 5 x 6
#> # Groups:   villageID [5]
#>   villageID perc_95 temp1 temp2 temp3 temp365
#>       <dbl>   <dbl> <dbl> <dbl> <dbl>   <dbl>
#> 1         1    96.2    70    86    98      79
#> 2         2    97.5    73    89    99      86
#> 3         3    93.9    71    82    96      75
#> 4         4    92.0    78    79    94      81
#> 5         5    90.8    90    91    89      85

reprex package (v0.2.1) 于 2019 年 2 月 27 日创建

【讨论】:

    【解决方案2】:

    在基础 R 中它只是(假设只有温度列中包含字符串“temp”):

     dfrm$temp95perc <- 
                apply( dfrm[ ,grep("temp", names(dfrm) )], #select just `tempNNN` columns
                          1, # row-wise calcs
                                quantile, probs=0.95) # give `quantile` a probs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-16
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      相关资源
      最近更新 更多