# 将 function 应用于值向量而不是 R 中的单个值

[英]Apply function to vector of values instead of single value in R

`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(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

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
``````

``````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

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
``````