我需要将R中的Mann Kendall趋势测试应用于大量(约100万)不同大小的时间序列。我已经创建了一个脚本,它从某个目录中的所有文件中获取时间序列(实际上是一个数字列表),然后将结果输出到.txt文件。
问题是我有大约100万个时间序列,因此创建100万个文件并不是很好。所以我认为将所有时间序列放在一个.txt文件中(例如用“#”之类的符号分隔)可能更易于管理。所以我有一个这样的文件:
1
2
4
5
4
#
2
13
34
#
...
我想知道,是否有可能在R中提取这样的系列(在两个“#”之间)然后应用分析?
修改
关注@acesnap提示我正在使用此代码:
library(Kendall)
a=read.table("to_r.txt")
numData=1017135
for (i in 1:numData){
s1=subset(a,a$V1==i)
m=MannKendall(s1$V2)
cat(m[[1]]," ",m[[2]], " ", m[[3]]," ",m[[4]]," ", m[[5]], "\n" , file="monotonic_trend_checking.txt",append=TRUE)
}
这种方法有效,但问题是计算需要很长时间。你能建议更快的方法吗?
答案 0 :(得分:2)
如果您在数据集进入较大文件时对其进行编号,则会使事情变得更容易。如果你这样做,你可以使用for循环和子集。
setNum data
1 1
1 2
1 4
1 5
1 4
2 2
2 13
2 34
... ...
然后执行以下操作:
answers1 <- c()
numOfDataSets <- 1000000
for(i in 1:numOfDataSets){
ss1 <- subset(bigData, bigData$setNum == i) ## creates subset of each data set
ans1 <- mannKendallTrendTest(ss1$data) ## gets answer from test
answers1 <- c(answers1, ans1) ## inserts answer into vector
print(paste(i, " | ", ans1, "",sep="" )) ## prints which data set is in use
flush.console() ## prints to console now instead of waiting
}
答案 1 :(得分:1)
这可能是一个更优雅的解决方案:
# Read in your data
x=c('1','2','3','4','5','#','4','5','5','6','#','3','6','23','#')
# Build a list of indices where you want to split by:
ind=c(0,which(x=='#'))
# Use those indices split the vector into a list
lapply(seq(length(ind)-1),function (y) as.numeric(x[(ind[y]+1):(ind[y+1]-1)]))
请注意,要使此代码生效,您必须在文件的最后添加“#”字符。