规范化应用于数据框的数据的功能出错

Error in function to normalize data applied to a data frame

我已经从 UCI 机器学习库下载了共享单车数据集,并尝试在 R 中实现多元线性回归。数据格式如下:

> head(data1)
  season mnth hr holiday weekday workingday weathersit temp  atemp  hum windspeed cnt
1      1    1  0       0       6          0          1 0.24 0.2879 0.81    0.0000  16
2      1    1  1       0       6          0          1 0.22 0.2727 0.80    0.0000  40
3      1    1  2       0       6          0          1 0.22 0.2727 0.80    0.0000  32
4      1    1  3       0       6          0          1 0.24 0.2879 0.75    0.0000  13
5      1    1  4       0       6          0          1 0.24 0.2879 0.75    0.0000   1
6      1    1  5       0       6          0          2 0.24 0.2576 0.75    0.0896   1

我正在尝试使用以下函数规范化特定列(尚未规范化):

normalize <- function(x) {
  return ((x - min(x)) / (max(x) - min(x)))
}

问题是当我 运行:

 dfNorm <- as.data.frame(lapply(data1["season", "mnth", "hr", "weekday", "weathersit"], normalize)) 

我收到以下错误:

Error in [.data.frame(data1, "season", "month", "hour", "weekday", "weathersit") : unused arguments ("weekday", "weathersit")

为什么会出现此错误,我该如何解决?

要就地修改,我会使用 dplyr::mutate。这样的事情应该有效:

library(dplyr)
dfNorm <- data1 %>% 
  mutate_at(.vars = vars(season, mnth, hr, weekday, weathersit),
            .funs = funs(normalize))

只需将 lapply 分配给新列:

df[c("season_norm", "mnth_norm", "hr_norm", "weekday_norm", "weathersit_norm")] <-
   lapply(df[c("season", "mnth", "hr", "weekday", "weathersit")], normalize)