我有一个包含61列的数据集(60个解释变量和1个响应变量)。
所有显式变量都是数值型的,响应是ex的分类(默认).Some。变量具有负值(财务数据),因此标准化比规范化似乎更明智。但是,在使用"apply“函数进行标准化时,我必须首先删除response变量,所以我这样做了:
模型<- read.table.
modelwithnoresponse <- model
modelwithnoresponse$Default <- NULL
means <- apply(modelwithnoresponse,2mean)
standarddeviations <- apply(modelwithnoresponse,2,sd)
modelSTAN <- scale(modelwithnoresponse,center=means,scale=standarddeviations)
到目前为止,数据是标准化的。但是,现在我想将response变量添加回"modelSTAN“。我看过一些关于dplyr、合并函数和rbind的帖子,但我不能很好地工作,所以响应将简单地作为最后一列添加到我的"modelSTAN“中。
有没有人有一个很好的解决方案来解决这个问题,或者可能有另一个变通办法来标准化它,而不是先删除response变量?
我对R很陌生,因为我是一名金融专业的学生,选修了R。
发布于 2021-02-02 19:56:51
如果要向modelSTAN
数据框中添加model$Default
列,可执行以下操作
# assign the column directly
modelSTAN$Default <- model$Default
# or use cbind for columns (rbind is for rows)
modelSTAN <- cbind(modelSTAN, model$Default)
但是,您根本不需要删除它。这里有一个替代方案:
modelSTAN <- model
## get index of response, here named default
resp <- which(names(modelSTAN) == "default")
## standardize all the non-response columns
means <- colMeans(modelSTAN[-resp])
sds <- apply(modelSTAN[-resp], 2, sd)
modelSTAN[-resp] <- scale(modelSTAN[-resp], center = means, scale = sds)
如果您对dplyr
感兴趣
library(dplyr)
modelSTAN <- model %>%
mutate(across(-all_of("default"), scale))
请注意,在dplyr
版本中,我没有费心保存原始的均值和SDs,如果您想要稍后进行反向转换,您仍然应该这样做。默认情况下,scale
将使用mean
和sd
。
https://stackoverflow.com/questions/66016616
复制