繁体   English   中英

在 R + 中缩放和居中多个列,为新列添加新名称

[英]Scale and center multiple columns in R + adding new names to the new columns

我有一个包含几列各种类(字符、因子和数字)的大型数据框。 可以使用以下代码复制数据帧的子集:

df <- structure(
  list(
                  id = c("1", "2", "3", "4", "5"), 
                  gender = structure(c(1L, 2L, 1L, 2L, 1L), levels = c("Female", "Male"), class = "factor"), 
                  age = c(78, 64, 79, 98, 82),
                  score1 = c(-0.019375, -0.025835, -0.029842, -0.029842, -0.027398),
                  score2 = c(0.0004892, -0.001254932, -0.00135780, -0.00312374, -0.00685426), 
                  score3 = c(-0.05938750, -0.1237563, -0.08442363, -0.09326243, -0.091492836)),
  row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

我想使用scale函数(base)标准化 score1、score2 和 score3,将它们添加到具有新名称的数据框中(在 score 前面添加 az)并将原始分数保留在数据框中。

到目前为止,我已经使用下面的代码创建了标准化分数,但我想使用函数或循环来使代码更高效,因为我的数据框还有几个要标准化的分数。

df$zscore1 <- scale(df$score1, center = TRUE, scale = TRUE)
df$zscore2 <- scale(df$score2, center = TRUE, scale = TRUE)
df$zscore3 <- scale(df$score3, center = TRUE, scale = TRUE)

任何建议如何解决这个问题?

编辑:

Sotos 的解决方案非常适合我提供的示例。 但是,分数列的名称不像提供的示例中那样有条理。 我为此道歉。 它们更像这样:

df <- structure(
  list(
                  id = c("1", "2", "3", "4", "5"), 
                  gender = structure(c(1L, 2L, 1L, 2L, 1L), levels = c("Female", "Male"), class = "factor"), 
                  age = c(78, 64, 79, 98, 82),
                  AD = c(-0.019375, -0.025835, -0.029842, -0.029842, -0.027398),
                  PD1 = c(0.0004892, -0.001254932, -0.00135780, -0.00312374, -0.00685426), 
                  DEM = c(-0.05938750, -0.1237563, -0.08442363, -0.09326243, -0.091492836)),
  row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

我寻求的输出如下:

df$zAD_2 <- scale(df$AD, center = TRUE, scale = TRUE)
df$zPD1_2 <- scale(df$PD1, center = TRUE, scale = TRUE)
df$zDEM_2 <- scale(df$DEM, center = TRUE, scale = TRUE)

你可以试试,

i1 <- -seq(3)
df[paste0('z', names(df)[i1], '_2')] <- scale(df[i1], center = TRUE, scale = TRUE)

df
# A tibble: 5 x 9
  id    gender   age      AD       PD1     DEM  zAD_2  zPD1_2   zDEM_2
  <chr> <fct>  <dbl>   <dbl>     <dbl>   <dbl>  <dbl>  <dbl>   <dbl>
1 1     Female    78 -0.0194  0.000489 -0.0594  1.64   1.04   1.35  
2 2     Male      64 -0.0258 -0.00125  -0.124   0.145  0.418 -1.45  
3 3     Female    79 -0.0298 -0.00136  -0.0844 -0.785  0.381  0.262 
4 4     Male      98 -0.0298 -0.00312  -0.0933 -0.785 -0.252 -0.122 
5 5     Female    82 -0.0274 -0.00685  -0.0915 -0.218 -1.59  -0.0447

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM