Scaling a numeric matrix in R with values 0 to 1

前端 未结 5 667
日久生厌
日久生厌 2020-12-09 10:43

Here is an excerpt of numeric matrix that I have

 [1,]   30 -33.129487   3894754.1 -39.701738 -38.356477 -34.220534
 [2,]   29 -44.289487  -8217525.9 -44.801         


        
5条回答
  •  悲&欢浪女
    2020-12-09 10:46

    Not the prettiest but this just got the job done, since I needed to do this in a dataframe.

    column_zero_one_range_scale  <- function(
    input_df,
    columns_to_scale #columns in input_df to scale, must be numeric
    ){
    
    input_df_replace <- input_df
    
    columncount <- length(columns_to_scale)
    for(i in 1:columncount){
    
    columnnum <- columns_to_scale[i]
    
    if(class(input_df[,columnnum]) !='numeric' & class(input_df[,columnnum])!='integer')
      {print(paste('Column name ',colnames(input_df)[columnnum],' not an integer or numeric, will skip',sep='')) }
    
    
    if(class(input_df[,columnnum]) %in% c('numeric','integer'))
    {
      vec <- input_df[,columnnum]
      rangevec <- max(vec,na.rm=T)-min(vec,na.rm=T)
      vec1 <- vec - min(vec,na.rm=T)
      vec2 <- vec1/rangevec
    }
    input_df_replace[,columnnum] <- vec2
    colnames(input_df_replace)[columnnum] <- paste(colnames(input_df)[columnnum],'_scaled')
    
    }
    
    return(input_df_replace)
    
    
    }
    

提交回复
热议问题