从数据框中删除异常值的功能
问题描述:
我想编写一个函数,该函数将输入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
. . . . .
. . . . .
答
你的问题是,你想将其分配到列表中时,使每一列的数据帧。这是不必要的。我们还可以通过逐个覆盖df
对象中的列来避免initialize-to-list-and-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)))
}
+0
这正是我所期待的。谢谢! –
http://stackoverflow.com/questions/12866189/calculating-the-outliers-in-r 这可能对你也有一定的用处。 想法是你创建一个数据框的功能,通过查找分位数,上下阈值来总结数据框并过滤掉该范围以外的最终数据集。 – InfiniteFlashChess