首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用R中的apply系列制作一个简单的脚本

如何使用R中的apply系列制作一个简单的脚本
EN

Stack Overflow用户
提问于 2018-03-07 06:17:49
回答 1查看 62关注 0票数 0

我需要使用R进行异常检测,但我认为我的代码非常长。我需要“找到异常点”和“完全异常点”。有人能简单地使用家庭申请吗?这里的代码

代码语言:javascript
复制
#Library
library(AnomalyDetection)
# Data Preparation
set.seed(1)
datex <- seq(as.Date("2017/01/01"), as.Date("2019/01/01"), by = "day")
x1 <- rf(731,3,4); x2 <- rf(731,3,4); x3 <- rf(731,3,4)
data.train <- data.frame(datex,x1,x2,x3,x4,x5)
# Find Anomaly x1
find.anomaly.x1 <- AnomalyDetectionTs(data.train[,c(1,2)],
                                      max_anoms = 0.3,
                                      direction = "both",
                                      alpha = 0.05,
                                      plot = F); find.anomaly.x1$anoms
# Find Anomaly x2
find.anomaly.x2 <- AnomalyDetectionTs(data.train[,c(1,3)],
                                      max_anoms = 0.3,
                                      direction = "both",
                                      alpha = 0.05,
                                      plot = F);find.anomaly.x2$anoms
# Find Anomaly x3
find.anomaly.x3 <- AnomalyDetectionTs(data.train[,c(1,4)],
                                      max_anoms = 0.3,
                                      direction = "both",
                                      alpha = 0.05,
                                      plot = F); find.anomaly.x3$anoms
# List Find Anomaly
find.anomaly

## Total Anomaly
# Total Anomaly x1
total.anomaly.x1 <- dim(find.anomaly.x1$anoms)[1]; total.anomaly.x1
# Total Anomaly x2
total.anomaly.x2 <- dim(find.anomaly.x2$anoms)[1]; total.anomaly.x2
# Total Anomaly x3
total.anomaly.x3 <- dim(find.anomaly.x3$anoms)[1]; total.anomaly.x3
# Total Anomaly
var.anom <- c("x1","x2","x3")
tot.anom.x <- c(total.anomaly.x1,total.anomaly.x2,total.anomaly.x3)
total.anomaly <- data.frame(var.anom,tot.anom.x)
total.anomaly
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-07 06:47:08

带有purrr包的解决方案:

代码语言:javascript
复制
library(purrr)

anomaly <- function(data, col) {
  x <- AnomalyDetectionTs(data[,c(1, col)],
                     max_anoms = 0.3,
                     direction = "both",
                     alpha = 0.05,
                     plot = F)
  x$anoms
}

find.anomaly <- map(2:4, ~ anomaly(data.train, col = .))
total.anomaly <- map(find.anomaly, ~ dim(.)[1])

以及使用lapply的R基解

代码语言:javascript
复制
find.anomaly <- lapply(2:4, function(x) anomaly(data.train, col = x))
total.anomaly <- lapply(find.anomaly, function(x) dim(x)[1])

re:注释,让total.anomaly和df一样:

代码语言:javascript
复制
find.anomaly <- map(2:6, ~ anomaly(data.train, col = .)) %>% setNames(names(data.train)[2:6])  
total.anomaly <- map_df(find.anomaly, ~ dim(.)[1])
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49145369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档