计算数据框中各列的第90个百分位数

时间:2015-12-04 17:20:34

标签: r dataframe reshape quantile

我正在尝试按样本日期计算所有站点粪便样本的第90个百分位数,跨数据框中的列。能够将其添加为新列但不是绝对必要的将是很好的。

我按以下方式重新排列数据,但我不知道这是否有必要。我很容易想象这种方式。

library(dplyr)
FecalData <- RawData %>%
select(Station, SampleDate, FecalColiform)

#Rearange by station
library(reshape2)
FecalbyStation <- dcast(FecalData, SampleDate ~ Station, fun.aggregate = mean, na.rm = TRUE)

这让我有了以下结构:

dput(FecalbyStation[1:5,])
structure(list(SampleDate = structure(c(6942, 6979, 7014, 7042, 
7070), class = "Date"), `114` = c(114.5, 2, 17, 7.9, 1.8), `115` = c(41, 
6.8, 33, 220, 4.5), `116` = c(64, 4, 14, 6.8, 1.8), `117` = c(33, 
2, 4.5, 1.8, 2), `118` = c(81.5, 2, 6.8, 33, 1.8), `119` = c(28, 
11, 4.5, 1.8, 2), `120` = c(64, 4.5, 11, 1.8, 1.8), `121` = c(31, 
4.5, 3.6, 13, 2), `122` = c(41, 2, 33, 13, 1.8), `123` = c(28, 
7.8, 2, 13, 1.8), `124` = c(NaN, 7.8, NaN, NaN, NaN), `125` = c(NaN, 
NaN, NaN, NaN, NaN), `126` = c(NaN, NaN, NaN, NaN, NaN), `127` = c(NaN, 
NaN, NaN, NaN, NaN), `128` = c(NaN, NaN, NaN, NaN, NaN), `129` = c(NaN, 
NaN, NaN, NaN, NaN), `614` = c(NaN, NaN, NaN, NaN, NaN), `615` = c(NaN, 
NaN, NaN, NaN, NaN), `639` = c(NaN, NaN, NaN, NaN, NaN), `758` = c(NaN, 
NaN, NaN, NaN, NaN)), .Names = c("SampleDate", "114", "115", 
"116", "117", "118", "119", "120", "121", "122", "123", "124", 
"125", "126", "127", "128", "129", "614", "615", "639", "758"
), row.names = c(NA, 5L), class = "data.frame")

我已经能够以这种方式找到row.means()并且反复调整此代码以尝试获得第90个百分位数。我一路上收到了几个不同的错误。这是我登陆的代码:

library(psych)
Q90 <- sapply(FecalbyStation, -1, quantile, probs=c(.90), na.rm = TRUE)

这给了我以下错误:

Error in match.fun(FUN) : '-1' is not a function, character or symbol

最终,我想将得出的第90个百分位数作为一个时间序列,以便我可以运行肯德尔或回归来调查该地区粪便水平的任何趋势。任何建议或建议都非常感谢。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将数据保存为长格式并按日期获得第90个百分位数:

library(dplyr)

RawData %>% group_by(SampleDate) %>%
  summarise(p90 = quantile(FecalColiform, probs=0.9, na.rm=TRUE))