why is my for loop function in r not working (trying to truncate outliers in the dataset) -
i'm trying replace extreme values nearest value in dataset. know ifelse () works better, wondering why loop not working.
truncate <- function(a){ m <- mean(a) sd <- sd(a) <- m+3*sd low <- m-3*sd a1 <- c() (i in 1:length(a)){ if (a[i] > up) { a1[i] = } if (a[i] < low){ a1[i] = low } else { a1[i] = a[i] } } return (a1) } <- c(1:100)
the for-loop working correctly , iterating through elements of 1:length(a)
. assuming giving a <- c(1:100)
input truncate()
, function isn't working because returns same value a
. seems because, using a
input, up
results in 137.5345
, low
results in -36.53448
. no values greater up
or less low
, else
statement reached.
also, copy-and-append pattern using generate a1
in for-loop , conditional statements computationally expensive. can vectorized , function can made more efficient follows:
truncate <- function(a) { m <- mean(a) sd <- sd(a) <- m+3*sd low <- m-3*sd a[a > up] <- a[a < low] <- low }
Comments
Post a Comment