我已经看到你问了一些关于按行操作的问题。你应该避免这种情况。 R遵循以下概念:列表示变量,行表示观察值。许多功能都根据这个概念进行了优化。如果您需要将宽输出或转置输出转换为文件,则可以在写入文件之前重新排列数据。
我假设你的数据实际上看起来如问题所示,但是你有多行。
df <- read.table(text="Team 01/01/2012 01/02/2012 01/03/2012 01/01/2012 01/04/2012 SD
Mean
A 100 50 40 NA 30 60 80
B 200 40 5 8 NA NA NA",check.names = FALSE,header=TRUE)
#needed because one date appears twice
df <- df[,]
#reshape the data
library(reshape2)
df <- melt(df,id="Team")
names(df)[2] <- "Date"
#remove the SD and Mean
df <- df[!df$Date %in% c("SD","Mean"),]
#function to detect outliers
outfun <- function(x) {
abs(x-mean(x,na.rm=TRUE)) > 3*sd(x,na.rm=TRUE)
}
#test if function works
outfun(c(200,rnorm(10)))
#use function over all data
df3$outlier.all <- outfun(df3$value)
#apply function for each team
library(plyr)
df3 <- ddply(df3,.(Team),transform,outlier.team=outfun(value))
结果:
Date Team value outlier.all outlier.team
1 01/01/2012 A 100 FALSE FALSE
2 01/02/2012 A 50 FALSE FALSE
3 01/03/2012 A 40 FALSE FALSE
4 01/01/2012.1 A NA NA NA
5 01/04/2012 A 30 FALSE FALSE
6 01/01/2012 B 200 FALSE FALSE
7 01/02/2012 B 40 FALSE FALSE
8 01/03/2012 B 5 FALSE FALSE
9 01/01/2012.1 B 8 FALSE FALSE
10 01/04/2012 B NA NA NA
如果您为我们提供了一个小样本数据用'dput(head(x))',那么我们可以将它剪切并粘贴到我们的浏览器中,并测试我们的解决方案。 – nograpes