R - Scaling numeric values only in a dataframe with mixed types

后端 未结 3 1301
野的像风
野的像风 2021-01-04 01:28

I am working with a data frame that has mixed data types (numeric and character) and also has a character key as the primary identifier. I\'d like to scale and center the n

相关标签:
3条回答
  • 2021-01-04 02:24

    Something like this should do what you want:

    library(MASS)
    ind <- sapply(anorexia, is.numeric)
    anorexia[ind] <- lapply(anorexia[ind], scale)
    
    0 讨论(0)
  • This can be done straightforwardly using dplyr::mutate_if:

    library(dplyr)
    
    iris %>%
        mutate_if(is.numeric, scale)
    
    0 讨论(0)
  • 2021-01-04 02:25

    This code below does not need any external library:

    # Scale all numeric columns in a data frame.
    # df is your data frame
    
    performScaling <- TRUE  # Turn it on/off for experimentation.
    
    if (performScaling) {
    
        # Loop over each column.
        for (colName in names(df)) {
    
            # Check if the column contains numeric data.
            if(class(df[,colName]) == 'integer' | class(df[,colName]) == 'numeric') {
    
                # Scale this column (scale() function applies z-scaling).
                df[,colName] <- scale(df[,colName])
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题