gpt4 book ai didi

r - 基于列名向量缩放列

转载 作者:行者123 更新时间:2023-12-04 08:36:29 25 4
gpt4 key购买 nike

set.seed(123)

dat <-
data.frame(year_ref = 2000:2004,
www_val1 = sample(5),
www_val2 = sample(5),
www_val3 = sample(5),
sat_val1 = sample(5),
sat_val2 = sample(5),
sat_val3 = sample(5),
ds_val1 = sample(5),
ds_val2 = sample(5),
ds_val3 = sample(5))
我想缩放名称在另一个向量中提供的所有列。例如。矢量 var_namesdssat ,我想缩放名称以它们开头的所有列
var_names <- c("ds", "sat")

library(dplyr)

dat %>%
dplyr::select(contains(var_names)) %>%
dplyr::mutate(scale(., center = T, scale = T))
但是,这是创建新列。我可以实现如下解决方案以便我可以进行更改吗
仅在原始数据框中,除了我不想硬编码列索引
dat[, 5:10] <- apply(dat[, 5:10], 2, function(x) scale(x, center = T, scale = T))

最佳答案

library(tidyverse)
set.seed(123)
dat <-
data.frame(year_ref = 2000:2004,
www_val1 = sample(5),
www_val2 = sample(5),
www_val3 = sample(5),
sat_val1 = sample(5),
sat_val2 = sample(5),
sat_val3 = sample(5),
ds_val1 = sample(5),
ds_val2 = sample(5),
ds_val3 = sample(5))
var_names <- c("ds", "sat")
dat %>%
dplyr::mutate_at(vars(starts_with(var_names)), ~scale(., center = T, scale = T))
# year_ref www_val1 www_val2 www_val3 sat_val1 sat_val2 sat_val3 ds_val1 ds_val2 ds_val3
# 1 2000 3 3 1 0.0000000 -0.6324555 -1.2649111 0.6324555 0.6324555 0.0000000
# 2 2001 5 5 3 -1.2649111 0.0000000 0.0000000 -0.6324555 -1.2649111 1.2649111
# 3 2002 2 2 2 0.6324555 0.6324555 0.6324555 0.0000000 1.2649111 -0.6324555
# 4 2003 4 4 5 -0.6324555 -1.2649111 -0.6324555 1.2649111 -0.6324555 -1.2649111
# 5 2004 1 1 4 1.2649111 1.2649111 1.2649111 -1.2649111 0.0000000 0.6324555

关于r - 基于列名向量缩放列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64773440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com