R:转义重复

时间:2019-03-31 19:45:22

标签: 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) &
  A10 < 1.5 * IQR(A10) | A10 > 1.5 * IQR(A10))
df_purged

我尝试过的方法(不起作用无法实现and运算符):

df_purgedd<- subset(df, for(col in c (A1,A4,A5,A8,A10)){[col] < 1.5 * IQR([col]) | A1 > 1.5 * IQR([col])})
df_purgedd

预先感谢

1 个答案:

答案 0 :(得分:1)

我们可以遍历感兴趣的列并应用该函数,然后将其Reduce &应用于单个逻辑向量

# 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)

或者在创建函数后的另一个选择是使用filter_at

library(dplyr)
df %>% 
    filter_at(vars(nm1), all_vars(f1))