如何从文本文件计算移动平均值?

时间:2013-03-15 10:54:27

标签: r dataframe zoo lapply moving-average

我有一个文本文件。我想做一些计算(移动平均),如下所示并写出结果。文本文件包含15列和601行。

columns <- paste0("X", 1:13)
ref <- read.table("D:\\DAS_asc.txt", sep="",header=TRUE)
library(zoo)
mean <- lapply(columns, function(column) { 
              rollapply(ref[[column]], 5, FUN = mean,na.rm=TRUE, fill=NA) })

当我输入“mean”来查看结果时,我发现计算结果不正确(我手动检查了!)。我认为它可能是moveave功能本身,但我检查并运作良好:

s=c(1,5,2,4)
rollapply(s, 2, FUN = mean,na.rm=TRUE, fill=NA)
[1] 3.0 3.5 3.0  NA
rollapply(s, 3, FUN = mean,na.rm=TRUE, fill=NA)
[1]       NA 2.666667 3.666667       NA

我想知道使用文本文件执行此操作时出了什么问题?

文件的前两行:

"0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14"
"2" 0.0493461075417879 0.0262911450465596 0.0426611743228151 0.0954854469641096 0.0933782886825547 0.218212200747129 0.285405481705908 0.226218243796976 0.146648210899044 0.115716572518044 0.0675501818197432 0.069120070466305 0.281314574594234 0.364434947521643 0.0124844383491671

2 个答案:

答案 0 :(得分:1)

如果您想要列的移动平均值,我看不到代码的问题。如果您的意思是13列中行的移动平均值,请在您的ref data.frame上使用apply代替...

movAvg <- t( apply( ref[,columns] , 1 , fun = function(x){ rollapply(x , width = 5, FUN = mean, na.rm=TRUE, fill=NA) } ) )

您应该返回一个数组,其中每列都是指定列的每行ref的移动平均值。我使用t()将其转换回行。

差异的虚拟示例

w <- 1:5
x <- 1:5
y <- 1:5
z <- 1:5
df <- data.frame( w ,x , y , z )
df
#     w x y z
#   1 1 1 1 1
#   2 2 2 2 2
#   3 3 3 3 3
#   4 4 4 4 4
#   5 5 5 5 5

cols <- c( "w" , "x" , "y" , "z" )
# Rolling average across columns using list of specified columns
laply( cols , function(x){  rollapply( df[[x]] , FUN = mean , width = 2 , na.rm=TRUE, fill=NA ) })
#          1   2   3   4  5
#   [1,] 1.5 2.5 3.5 4.5 NA
#   [2,] 1.5 2.5 3.5 4.5 NA
#   [3,] 1.5 2.5 3.5 4.5 NA
#   [4,] 1.5 2.5 3.5 4.5 NA 

# Which is the same as...
t( apply( df[ , cols] , 2, function(x){ rollapply( x , width = 2, FUN = mean, na.rm=TRUE, fill=NA) } ) )
#     [,1] [,2] [,3] [,4] [,5]
#   w  1.5  2.5  3.5  4.5   NA
#   x  1.5  2.5  3.5  4.5   NA
#   y  1.5  2.5  3.5  4.5   NA
#   z  1.5  2.5  3.5  4.5   NA

# Rolling average across rows...
t( apply( df[,cols] , 1 , FUN = function(x){ rollapply( x , FUN = mean , width = 2 , na.rm=TRUE, fill=NA  ) } ) )

答案 1 :(得分:1)

试试这个:

columns <- paste0("X", 1:13)
ref <- read.table("D:\\DAS_asc.txt", sep="",header=TRUE)
library(zoo)

movingaverages<-lapply( ref[,columns], function(column) { 
    rollapply(column, 5, FUN =  mean,na.rm=TRUE, fill=NA) } )

#OR
movingaverages<-apply( ref[,columns], 2, function(column) { 
    rollapply(column, 5, FUN =  mean,na.rm=TRUE, fill=NA) } )

# substract from old values:
ref[,columns]<-ref[,columns]-movingaverages

# note, movingaverages is not a data.frame
# you can convert it to such like this:

data.frame(movingaverages)

编辑:OP想要从旧值中减去结果。