从 DataFrame 中删除异常值的函数

Function to remove Outliers from a DataFrame

我想编写一个函数,它将 data.frame 作为输入,return 一个新的 data.frame 已经使用来自预测的 tsclean() 函数替换了异常值包。

对于示例输入df(包含明显的异常值):

df <- data.frame(col1 = runif(24, 400, 700),
                 col2 = runif(24, 350, 600),
                 col3 = runif(24, 600, 940),
                 col4 = runif(24, 2000, 2600),
                 col5 = runif(24, 950, 1200))

colnames(df) <- c("2to2", "2to6", "17to9", "20to31", "90to90")
df$`2to2`[[12]]=10000
df$`17to9`[[20]]=6000
df$`20to31`[[8]]=12000

我一直在尝试解决这个问题

clean_ts <- function(df, frequency = 12, start = c(2014, 1), end = c(2015, 12)) {

  ts <- ts(df, frequency = frequency, start = start, end = end)
  results <- list()

  for (i in 1:ncol(ts)) {
    clean <- as.data.frame(tsclean(ts[,i]))
    results[[i]] <- as.data.frame(cbind(clean))
  }
  return(results)
}

我知道这是错误的。我希望我的函数 return 具有与输入 data.frame 相同的维度和列名的 data.frame,而不是 returning 列表。我只想根据 tsclean() 函数替换 data.frame() 的列。因此,从示例中我的输出将具有以下形式:

2to2  2to6  17to9  20to31  90to90
 .     .     .       .       .
 .     .     .       .       .

您的问题是您在将每一列分配给列表时试图将其设为数据框。这是不必要的。我们还可以通过一次一个地覆盖 df 对象中的列来避免初始化列表和绑定工作流。

clean_ts <- function(df, frequency = 12, start = c(2014, 1), end = c(2015, 12)) {

  ts <- ts(df, frequency = frequency, start = start, end = end)

  for (i in 1:ncol(ts)) {
    df[, i] <- tsclean(ts[, i])
   }
  return(df)
}

更简洁,我们可以使用lapply来隐藏循环:

clean_ts <- function(df, frequency = 12, start = c(2014, 1), end = c(2015, 12)) {
  ts <- ts(df, frequency = frequency, start = start, end = end)
  return(as.data.frame(lapply, ts, tsclean)))
}