我有一个很大的数据框,其中有几列变量类(字符、因子和数字).可以使用以下代码再现数据帧的子集:

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,使用新名称将它们添加到数据框中(在分数前面添加一个z),并将原始分数保留在数据框中.

到目前为止,我已经用下面的代码创建了规范化的分数,但希望使用函数或循环来提高代码的效率,因为我的数据框架还有几个分数需要标准化.

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

R相关问答推荐

如何使用rmarkdown和kableExtra删除包含折叠行的表的第一列的名称

根据模式将一列拆分为多列,并在R中进行拆分

在数学中正确显示摄氏度、开氏度或华氏度

为什么横向页面会导致officeverse中的页码/节头/页脚出现问题?

在R中为马赛克图中的每个字段着色

在ggplot中为不同几何体使用不同的 colored颜色 比例

从一个列表的框架中移除列表包装器

使用R中的正则表达式将一列分割为多列

R Read.table函数无法对制表符分隔的数据正常工作

如何创建累加到现有列累计和的新列?

如何在R中改变fviz_pca_biplot中圆的边界线的 colored颜色 ?

使用R将简单的JSON解析为嵌套框架

Geom_arcbar()中出错:找不到函数";geom_arcbar";

R将函数参数传递给ggploy

R:如何在数据集中使用Apply

具有自定义仓位限制和计数的GGPLATE直方图

使用卡环从R中的列中删除单位(&C)

在子图内和子图之间对齐行数不均匀的表格罗布对

如何 suppress 条形图中的零条?

使用r box包一次加载所有功能