How to improve the operation of the function if()

Hi Community R,

in Table “A”, in Column “i” I have data that I would like to analyze. In the last Column of Table “A” are the values 0. I would like to replace these values to “1”, if in a given row in the Column “i” the value will turns out to be outlier.

How can I improve this code to make it effective and what I do wrong ? This code is very slow.

A[,ncol(A)] = lapply(A[,ncol(A)], FUN=function(y){

I would use the vectorized ifelse() function. I also calculated all of the static values outside of the ifelse. I do not know if that actually speeds up the calculation but it is at lease easier to read, I think. I made a small data frame to test the code, so I set i to 1.

A <- data.frame(Val = rnorm(10000), Flag = 0)
IQR_Val <- IQR(A[,i])*1.5
UPPER_Q <- quantile(A[,i],0.75) 
LOWER_Q <- quantile(A[,i],0.25) 
A[,ncol(A)] = ifelse((A$Val > UPPER_Q + IQR_Val) |
                       (A$Val < LOWER_Q - IQR_Val), 1, 0)
1 Like

Hello FJCC. Your help is invaluable and your code works. Thanks :blush:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.