使用across()与scale()时出现异常列名及数据类型问题求助
解决tidyverse中mutate+across+scale生成矩阵列与异常列名的问题
问题根源:scale()函数默认返回列矩阵(matrix),tibble会将这类列显示为列名[,1]格式,同时保留矩阵数据类型,导致列名和类型不符合预期。
快速解决方案(最常用)
在scale()外层包裹as.numeric(),将矩阵转为数值向量,同时保证标准化逻辑不变:
library(tidyverse) roster <- tibble( Student = c("John Davis", "Angela Williams", "Bullwinkle Moose", "David Jones", "Janice Markhammer", "Cheryl Cushing", "Reuven Ytzrhak", "Greg Knox", "Joel England", "Mary Rayburn"), Math = c(502, 600, 412, 358, 495, 512, 410, 625, 573, 522), Science = c(95, 99, 80, 82, 75, 85, 80, 95, 89, 86), English = c(25, 22, 18, 15, 20, 28, 15, 30, 27, 18) ) roster |> mutate(across( .cols = c(Math, Science, English), .fns = ~ as.numeric(scale(.x)), .names = "z_{.col}" ))
替代方案(手动实现标准化)
如果不想依赖scale()的矩阵返回值,可以手动计算标准化得分,直接返回数值向量:
roster |> mutate(across( .cols = c(Math, Science, English), .fns = ~ (.x - mean(.x, na.rm = TRUE)) / sd(.x, na.rm = TRUE), .names = "z_{.col}" ))
两种方法都能生成正确命名的数值列,新列名会是z_Math、z_Science、z_English,数据类型也会变成普通数值型。
内容的提问来源于stack exchange,提问作者Grasshopper_NZ
相关产品推荐
相关产品推荐

