在 Dataframe 中缩放和替换

Scale & replace in Dataframe

我需要从我的数据框中扩展一些列,我找到了一个完美完成它的函数。所以我的问题是如何替换数据框中的缩放列?是否有特定的功能,或者我应该以不同的方式做到这一点?

df <- raw_data %>%
  select(CLIENTNUM:Avg_Utilization_Ratio) %>%
  rename(Customer_Nr = CLIENTNUM,
         Customer_Act = Attrition_Flag,
         Total_Product_Count = Total_Relationship_Count)


scaled <- scale(select(df, Customer_Nr, Customer_Age, Dependent_count, Months_on_book,
                       Total_Product_Count, Months_Inactive_12_mon, Contacts_Count_12_mon, Credit_Limit,
                       Total_Revolving_Bal, Avg_Open_To_Buy, Total_Amt_Chng_Q4_Q1, Total_Trans_Amt,
                       Total_Trans_Ct)
                , center = T, scale = T)

创建列名的字符向量并仅在这些列上应用scale

cols <- c('Customer_Nr', 'Customer_Age', 'Dependent_count' .....)
df[cols] <- scale(df[cols])

使用 mtcars 数据集的示例:

df <- mtcars
cols <- c('mpg', 'disp')
df[cols] <- scale(df[cols])
df

#                        mpg cyl    disp  hp drat   wt qsec vs am gear carb
#Mazda RX4            0.1509   6 -0.5706 110 3.90 2.62 16.5  0  1    4    4
#Mazda RX4 Wag        0.1509   6 -0.5706 110 3.90 2.88 17.0  0  1    4    4
#Datsun 710           0.4495   4 -0.9902  93 3.85 2.32 18.6  1  1    4    1
#Hornet 4 Drive       0.2173   6  0.2201 110 3.08 3.21 19.4  1  0    3    1
#Hornet Sportabout   -0.2307   8  1.0431 175 3.15 3.44 17.0  0  0    3    2
#Valiant             -0.3303   6 -0.0462 105 2.76 3.46 20.2  1  0    3    1
#...
#...