仅缩放某些列R [英] Scale only certain columns R

查看:40
本文介绍了仅缩放某些列R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅缩放(x)数据框的某些列?我有一个包含7列的数据框,我只想缩放第3列和第6列.其余的应该保持不变.

How can I scale(x) only certain columns of a dataframe? I have a dataframe with 7 columns and I want to scale only column 3 and 6. The rest should stay as it is.

推荐答案

我们可以使用 lapply 来做到这一点.对感兴趣的列进行子集设置,使用 lapply 遍历它们,然后将输出分配回数据子集.在这里,我们使用 c ,因为 scale 的输出是带有单个列的 matrix .使用 c as.vector ,将其转换为 vector

We can do this with lapply. Subset the columns of interest, loop through them with lapply, assign the output back to the subset of data. Here, we are using c because the outpuf of scale is a matrix with a single column. Using c or as.vector, it gets converted to vector

df[c(3,6)] <- lapply(df[c(3, 6), function(x) c(scale(x)))


或者另一个选择是 dplyr

library(dplyr)
df %>%
   mutate_at(c(3,6), funs(c(scale(.))))

这篇关于仅缩放某些列R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆