我经常要处理以下问题:
目前,我的工作流程是kludgy:我使用索引向量,然后使用部分赋值来仅缩放列车集的某些列。我在训练集上存储了缩放操作的平均值和标准差,我用它们来缩放测试集。我想知道是否有更简单的方法,无需安装caret
(由于一系列原因,我不是caret
的忠实粉丝,我绝对不会开始使用它对于这个问题)。
这是我目前的工作流程:
# define dummy train and test sets
train <- data.frame(letters = LETTERS[1:10], months = month.abb[1:10], numbers = 1:10,
x = rnorm(10, 1), y = runif(10))
test <- train
test$x <- rnorm(10, 1)
test$y <- runif(10)
# names of variables I don't want to scale
varnames <- c("letters", "months", "numbers")
# index vector of columns which must not be scaled
index <- names(train) %in% varnames
# scale only the columns not in index
temp <- scale(train[, !index])
train[, !index] <- temp
# get the means and standard deviations from temp, to scale test too
means <- attr(temp, "scaled:center")
standard_deviations <- attr(temp, "scaled:center")
# scale test
test[, !index] <- scale(test[, !index], center = means, scale = standard_deviations)
是否有更简单/更惯用的方式来做到这一点?
答案 0 :(得分:0)
这是一个很好的问题,我已经尝试了很多答案。 我认为这是一个更优雅的代码:
train0=train%>%select(-c(letters, months, numbers))%>%as.matrix%>%scale
means <- attr(train0, "scaled:center")
standard_deviations <- attr(train0, "scaled:center")
train0=cbind(select(train,c(letters, months, numbers)),train0)
test0=test%>%select(-c(letters, months, numbers))%>%as.matrix%>%scale(center = means, scale = standard_deviations)
test0=cbind(select(test,c(letters, months, numbers)),test0)
我努力使用mutate_at
以避免cbind
额外代码,但不缺