【问题标题】:Function to remove Outliers from a DataFrame从 DataFrame 中删除异常值的函数
【发布时间】:2016-06-15 23:48:07
【问题描述】:

我想编写一个函数,它将data.frame 作为输入并返回一个新的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)
}

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

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

【问题讨论】:

  • stackoverflow.com/questions/12866189/… 这可能对你也有用。想法是您创建一个函数,该函数接收一个数据帧,通过查找分位数、上限和下限阈值来总结数据帧,并过滤该范围之外的最终数据集..

标签: r for-loop dataframe outliers


【解决方案1】:

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

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)))
}

【讨论】:

  • 这正是我想要的。谢谢!
猜你喜欢
  • 2019-03-22
  • 2020-05-06
  • 2018-12-13
  • 2016-08-20
  • 1970-01-01
  • 2021-12-16
  • 2016-06-20
  • 2021-01-16
相关资源
最近更新 更多