Это будет быстрее, чем у вас сейчас:
NROW=1e5
NCOL=12
df = data.frame(
time = rnorm(NROW),
matrix(rnorm(NCOL*NROW),nrow=N)
)
colnames(df)[2:ncol(df)] = LETTERS[1:NCOL]
change_outlier <- function(x) {
H <- 3 * IQR(x, na.rm = T)
out1 <- round(median(x) - H)
out2 <- round(median(x) + H)
x[x < out1] <- out1
x[x > out2] <- out2
mean(x)
}
#set a new column with NA
df$new = NA
# if time > 0, do something on columns A to D, which is 2:5
df$new[df$time>0] = apply(df[df$time>0,2:5], 1, change_outlier)
# others, do on columns E to others
df$new[!(df$time>0)] = apply(df[!df$time>0,6:ncol(df)], 1, change_outlier)