Normalizing a variable

I would like to normalize a variable but when I choose one specific variable within my df the following function does not work:

fun_range <- function(x) {                              # Create user-defined function
  (x - min(x)) / (max(x) - min(x))
}

I use aut <- fun_range(x = aut$SupDem) here my df is 'aut' and my variable is SupDem.

@korkut_keles Hi, aut <- fun_range(aut$SupDem), it maybe work,iput your data directly. And notice if there is NA in your original data.

The following code ends with NAs for SupDem variable.

fun_range <- function(x) {                              # Create user-defined function
  (x - min(x)) / (max(x) - min(x))
}

aut$SupDem <- fun_range(aut$SupDem)

Did not work sadly this one as well. Because I only want to rescale SupDem making it between 1-0 within the dataset. What I mean is that I want that specific variable to be between 1-0 numeric variable. The following code works well:

aut$SupDem <- scale(aut$SupDem, center = min(aut$SupDem), scale = diff(range(aut$SupDem)))

@korkut_keles good idea. How about this code? I successfully get the result use my own data.

fun_range<-function(x) {                
  (x - min(x,na.rm = TRUE)) / (max(x,na.rm = TRUE) - min(x,na.rm = TRUE))
}
aut$SupDem <- fun_range(aut$SupDem)

Created on 2023-02-11 with reprex v2.0.2

This code perfectly worked! The function was wrong. Many thank! @Comede_way

You are welcome. Would you mind click the button of solution under that code for me if it has solved your question? Thank you!

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.