你如何在 R 中的用户定义函数中使用任何 if_any 或类似的东西?

How do you use any, if_any, or something analogous in a user defined function in R?

我正在将函数应用于数据框。如果任何一组参数不是 NA,我想应用某个函数。也就是说,如果以下任何一项:P1TNP1TPP1TSSP2TNP3TNP3TPP3TSS不 NA,则 运行 第二个和第三个 ifelse 语句中的第一个语句。通常,对于此操作,我会使用 any 或 if_any,但我不知道如何在函数中执行此操作。

我能想到的最好的办法是 !is.na(P1TN) & !is.na(P2TN) & !is.na(P3TN) & !is.na(P1TP) & !is.na(P3TP) & !is.na(P1TSS) & !is.na(P3TSS),这不是很好...

我可以在函数之前更改数据,但理想情况下我想在内部进行:

df$P <- apply(df[,c("P1TN","P1TP","P1TSS","P2TN","P3TN","P3TP","P3TSS")], 1, 
              function(r) ifelse(all(is.na(r)),"No", "Yes"))

示例数据:

df <-data.frame(L=c(100,200,800,1600), P=c("Yes", "No", "Yes", NA),
                P1TN=c(220,NA,640,99), P1TP=c(160,NA,120,33), P1TSS=c(1200,NA,1600,205), 
                P2TN=c(220,NA,640,NA), 
                P3TN=c(NA,NA,640,NA),  P3TP=c(360,NA,640,NA), P3TSS=c(NA,NA,640,NA),
                Ph=c("As-Built","Design","Design","Complete"),
                BD=c("2018-01-20",NA,NA,"2020-08-16"))

函数:

IA <- function(L, P ,P1TN, P1TP, P1TSS, P2TN, P3TN, P3TP, P3TSS, Ph, BD){
  ifelse(is.na(BD) & Ph %in% c("Design","Construction Document","Schematic Design","Design Development","Concept") | BD >= as.POSIXct("2020-07-01 00:00:00"),
    ifelse(P=="Yes" | is.na(P) & !is.na(P1TN) & !is.na(P2TN) & !is.na(P3TN) & !is.na(P1TP) & !is.na(P3TP) & !is.na(P1TSS) & !is.na(P3TSS),
      ((sum(P1TN,P2TN,P3TN,na.rm=T)/18.08) + (sum(P1TP,P3TP,na.rm=T)/2.23) + (sum(P1TSS,P3TSS,na.rm=T)/8046))/3, L*0.02),
    ifelse(P=="Yes" | is.na(P) & !is.na(P1TN) & !is.na(P2TN) & !is.na(P3TN) & !is.na(P1TP) & !is.na(P3TP) & !is.na(P1TSS) & !is.na(P3TSS),
      ((sum(P1TN,P2TN,P3TN,na.rm=T)/7.69) + (sum(P1TP,P3TP,na.rm=T)/1.91) + ((sum(P1TSS,P3TSS,na.rm=T)/0.43)/2000))/3, L*0.02))
} 

格式化日期和运行函数:

df$BD <- as.POSIXct(df$BD)
df$IA <- IA(df$L, df$P, df$P1TN, df$P1TP, df$P1TSS, df$P2TN, df$P3TN, df$P3TP, df$P3TSS, df$Ph, df$BD)
df

你可以替换

!is.na(P1TN) & !is.na(P2TN) & !is.na(P3TN) & !is.na(P1TP) & !is.na(P3TP) & !is.na(P1TSS) & !is.na(P3TSS) 

来自

complete.cases(df[,3-9])

此致,