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

Calculate 90th percentile across columns in a data frame

我正在尝试按样本日期计算所有站点粪便样本的第 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 个百分位数作为时间序列,这样我就可以 运行 对其进行肯德尔或回归,以调查该地区粪便水平的任何趋势。非常感谢任何建议或建议。

谢谢!

您可以以长格式保存数据并按日期获取第 90 个百分位数,如下所示:

library(dplyr)

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