【发布时间】: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