
[英]R - Comparing values in a vector to a single value (Using the apply family)
[英]Apply function to vector of values instead of single value in R
我写了一个function来计算PAFPM2.5
这个 function 工作正常。
但是,在我尝试将 function 应用于一组矢量值的最后一步中出现致命错误。 在代码的第一行,我手动输入了值,代码在那里工作正常。 但我不需要 1 个值,但我需要 PAFPM2.5 来获取数百个值,从向量中读取 RR.low、RR.up 和 RR.est,如您在代码的第二行中所见。
不幸的是,这会导致错误:“PAF.summary 错误(low = sectors$RR.low,up = sectors$RR.up,est = sectors$RR.est):未使用 arguments(low = sectors$RR.low , up = sectors$RR.up, est = sectors$RR.est)”
为清楚起见,sectors$RR.low 包含大约 100 个 RR.low 值,其他列也是如此。
PAFPM2.5<-PAF.summary(RR.low = 1.4, RR.up = 1.6, RR.est=1.5) #PM2.5
PAFPM2.5<-PAF.summary(low = sectors$RR.low, up = sectors$RR.up, est=sectors$RR.est) #PM2.5
##full script
library(readxl)
library(triangle)
sectors <- read_excel("sectors.xlsx") ##of handmatig inlezen via de knop (import dataset)
RR.low <- numeric()
RR.up <- numeric()
RR.est <- numeric()
RR.low <- sectors$RR.low
RR.up <- sectors$RR.up
RR.est <- sectors$RR.est
PAF.summary<-function(RR.low,RR.up,RR.est){
### RR.est is the point estimate of the RR
### (RR.low,RR.up) is the CI of the RR
# relative risk
r <- rtriangle(10000,a=RR.low,b=RR.up,c=RR.est)
# proportion of population with risk factor
p<-1.0 #in a statistical sector, 100% exposed to mean concentration within sector
# traditional PAF method
PAF<-(p*(r-1))/(p*(r-1)+p)
return(quantile(PAF,c(0.025,0.5,0.975)))
}
PAFPM2.5<-PAF.summary(RR.low = 1.4, RR.up = 1.6, RR.est=1.5) #PM2.5 ###works fine
##should be converted to store many values based on the sectors file
PAFPM2.5<-PAF.summary(RR.low = sectors$RR.low, RR.up = sectors$RR.up, RR.est=sectors$RR.est) #PM2.5
一种方法是矢量化 function:
PAF.summary<-function(RR.low,RR.up,RR.est,id=NA){
### RR.est is the point estimate of the RR
### (RR.low,RR.up) is the CI of the RR
library(triangle)
# relative risk
rtriangle2 <- Vectorize(rtriangle)
r <- rtriangle2(10000,a=RR.low,b=RR.up,c=RR.est)
# proportion of population with risk factor
p<-1.0 #in a statistical sector, 100% exposed to mean concentration within sector
# traditional PAF method
PAF<-(p*(r-1))/(p*(r-1)+p)
output <- as.data.frame(t(apply(PAF,2,quantile,c(0.025,0.5,0.975))))
if(!all(is.na(id))){
output <- cbind(id,output)
}
return(output)
例子:
RR.low <- c(1.26,1.19)
RR.est <- c(1.34,1.25)
RR.up <- c(1.42,1.38)
SECTOR <- c("A575","A576")
PAF.summary(RR.low = 1.4, RR.up = 1.6, RR.est=1.5)
2.5% 50% 97.5%
1 0.2970301 0.3332704 0.3665127
PAF.summary(RR.low, RR.up, RR.est,SECTOR)
id 2.5% 50% 97.5%
1 A575 0.2175932 0.2538054 0.2865436
2 A576 0.1712424 0.2119270 0.2623992
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.