-2

I'm trying to normalize the variable by using normalized = 30 * (x-min(x))/(max(x)-min(x)) to 0-30 scale.

In python it would be:

new_escore = esg_funds['Portfolio Environmental Score'].apply(lambda x: 30*(x-esg_funds['Portfolio Environmental Score'].min())/(esg_funds['Portfolio Environmental Score'].max()-esg_funds['Portfolio Environmental Score'].min()))

esg_funds is my data, and 'Portfolio Environmental Score' is the variable.

How do I use apply() function here?

zephryl
  • 14,633
  • 3
  • 11
  • 30
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. [Requests for code translation](https://meta.stackoverflow.com/questions/296119/is-how-do-i-convert-code-from-this-language-to-this-language-too-broad) are off topic. Forget about the python code, describe what you need to accomplish in R as it's own task. – MrFlick Nov 07 '22 at 17:39
  • Think of a `lambda` as just a function with no name. Thus, make a function in R and provide it the data it needs to compute the `new_score` then pass that data in, voila! – KDecker Nov 07 '22 at 17:39

1 Answers1

0

There's no need to use *apply() thanks to R's vectorized operations. Instead you can do:

new_escore <- 30 * (
    esg_funds[['Portfolio Environmental Score']] - min(esg_funds[['Portfolio Environmental Score']])
  ) / (
    max(esg_funds[['Portfolio Environmental Score']] - min(esg_funds[['Portfolio Environmental Score']]))
  )

Or more succinctly,

normalize <- function(x) 30 * (x - min(x)) / (max(x) - min(x))

new_escore <- normalize(esg_funds[['Portfolio Environmental Score']])
zephryl
  • 14,633
  • 3
  • 11
  • 30