3

I am only a few days old in the R ecosystem and trying to figure out a way to add dynamic column for each numeric column found in the original dataframe.

I have succesfully written a way to change the value in the existing column in the dataframe but what I need is to put those calculated values into a new column rather than overwriting the existing one.

Here is what I've done so far,

myDf <- read.csv("MyData.csv",header = TRUE)

normalize <- function(x) {
    return ((x - min(x,na.rm = TRUE)) / (max(x,na.rm = TRUE) - min(x,na.rm = TRUE)))
}

normalizeAllCols <- function(df){
    df[,sapply(x, is.numeric)] <- lapply(df[,sapply(df, is.numeric)], normalize)
    df
}

normalizedDf<-normalizeAllCols(myDf)

I came with above snippet (with a lot of help from the internet) to apply normalize function to all numeric columns in the given data frame. I want to know how to put those calculated values into a new column in the data frame. (in the given snippet I'd like to know how to put normalized value in a new column like "norm" + colname ).

1 Answer 1

2

You can find the column names which are numeric and use paste0 create new columns.

normalizeAllCols <- function(df){
  cols <- names(df)[sapply(df, is.numeric)]
  df[paste0('norm_', cols)] <- lapply(df[cols], normalize)
  df
}

normalizedDf<-normalizeAllCols(myDf)

In dplyr you can use across to apply a function to only numeric columns directly.

library(dplyr)
normalizeAllCols <- function(df){
 df %>%
    mutate(across(where(is.numeric), list(norm = ~normalize)))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.