Home > Software engineering >  'apply' function in R
'apply' function in R

Time:05-18

I want to apply the following normalization function in 'R': normalize <- function(x) {return ((x - min(x)) / (max(x) - min(x)))}

However, my dataset has 68 observations and 960 variables, and some NaN here and there. Of course, before applying the function I would like to remove these NaNs

So, I used the following function: df_normalized <- apply(df, 1, normalize, na.rm=TRUE)

However, the na.rm=TRUE function is not being recognized.

CodePudding user response:

Two options -

  1. Change the normalize function to ignore the NA values in max, min functions.
normalize <- function(x) {
  (x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
}
  1. Without changing the normalize function pass only non-NA values
df_normalized <- apply(df, 1, function(x) normalize(na.omit(x)))
  • Related