Mimayuki
Mimayuki

Reputation: 127

R: Escaping Repetition

I am trying to avoid repetition.

My code:

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

What I have tried (not working can't implement and operators):

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

Thanks in advance

Upvotes: 1

Views: 116

Answers (1)

akrun
akrun

Reputation: 887611

We can loop through the columns of interest and apply the function, then Reduce it to a single logical vector with &

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

Or another option after creating the function is to use filter_at

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

Upvotes: 1

Related Questions