R:逃避重复

R:逃避重复,r,loops,R,Loops,我尽量避免重复 我的代码: df_purged <- subset(df, A1 < 1.5 * IQR(A1) | A1 > 1.5 * IQR(A1) & A4 < 1.5 * IQR(A4) | A4 > 1.5 * IQR(A4) & A5 < 1.5 * IQR(A5) | A5 > 1.5 * IQR(A5) & A8 < 1.5 * IQR(A8) | A8 > 1.5 * IQR(A8

我尽量避免重复

我的代码:

df_purged <- subset(df, 
  A1 < 1.5 * IQR(A1) | A1 > 1.5 * IQR(A1) &
  A4 < 1.5 * IQR(A4) | A4 > 1.5 * IQR(A4) &
  A5 < 1.5 * IQR(A5) | A5 > 1.5 * IQR(A5) &
  A8 < 1.5 * IQR(A8) | A8 > 1.5 * IQR(A8) &
  A10 < 1.5 * IQR(A10) | A10 > 1.5 * IQR(A10))
df_purged

提前感谢

我们可以循环浏览感兴趣的列并应用函数,然后
使用
&

# create a function based on the logic
f1 <- function(x) x < 1.5 * IQR(x) | x > 1. 5 * IQR(x)
# loop through the columns with lapply, apply the 'f1' 
# and Reduce it to single logical vector
nm1 <- paste0("A", c(1, 4, 5, 8, 10))
i1 <- Reduce(`&`, lapply(df[nm1], f1))
# subset the rows
out <- subset(df, i1)

非常好用。谢谢你的回复。但是,您能解释一下替代解决方案中的情况吗?@Mimayuki在第二个解决方案中,
all_vars
检查每行中的列是否都满足条件,并且仅当它保留该行时
# create a function based on the logic
f1 <- function(x) x < 1.5 * IQR(x) | x > 1. 5 * IQR(x)
# loop through the columns with lapply, apply the 'f1' 
# and Reduce it to single logical vector
nm1 <- paste0("A", c(1, 4, 5, 8, 10))
i1 <- Reduce(`&`, lapply(df[nm1], f1))
# subset the rows
out <- subset(df, i1)
library(dplyr)
df %>% 
    filter_at(vars(nm1), all_vars(f1))