我试图将ccf(互相关函数)的结果写入数据框并打印。此代码适用于第一次迭代:
ccftable <- data.frame()
for (i in unique(Data$SeasAlltxt)){
subdata1 <- subset(Data, SeasAlltxt == i)
for (j in unique(Data$ALSCIDtxtall)){
subdata2 <- subset(subdata1, ALSCIDtxtall == j)
ccfvalues = ccf(x = subdata2$NO3_AVG, y = subdata2$MaxDepth_m, plot = FALSE, lag.max = 0, na.action = na.pass, ylab = "CCF: Lake NO3 vs. Snow Depth", main = paste0(j, ": ", i))
ccftable <- rbind(ccftable,c(i,j,ccfvalues))
print (ccftable)
write.csv(ccftable, file = "CCF_NO3vsSnowDepth_Stats.csv")
}
}
在后续迭代中,rbind函数失败,因为它看到前两个头字段的不同名称。这是&#34; print(ccftable)&#34;:
的输出 X.Winter. X.020058x. acf type n.used lag seriessnames
2 Winter 020058x 0.1454731 correlation 20 0 X subdata2$NO3_AVG & subdata2$MaxDepth_m
Error in match.names(clabs, nmi) : names do not match previous names
前两个标题字段名称不正确,#34; X.Winter。&#34;和&#34; X.020058x。&#34;。这些应该被命名为&#34; SeasAlltxt&#34;和&#34; ALSCIDtxtall&#34;,它们是变量i和j的字段名称。如果我可以进行此更改,那么rbind将看到相同的标题名称并在每次迭代时适当追加。
有关如何完成此任务的任何建议?
答案 0 :(得分:0)
您可以使用
设置列名称ccftable <- data.frame()
for (i in unique(Data$SeasAlltxt)){
subdata1 <- subset(Data, SeasAlltxt == i)
for (j in unique(Data$ALSCIDtxtall)){
subdata2 <- subset(subdata1, ALSCIDtxtall == j)
ccfvalues = ccf(x = subdata2$NO3_AVG, y = subdata2$MaxDepth_m, plot = FALSE, lag.max = 0, na.action = na.pass, ylab = "CCF: Lake NO3 vs. Snow Depth", main = paste0(j, ": ", i))
tempvalues <- data.frame(c(i,j,ccfvalues))
colnames(tempvalues) <- c('SeasAlltxt', 'ALSCIDtxtall', 'acf', 'type', 'n.used', 'lag', 'series', 'snames')
ccftable <- rbind(ccftable,tempvalues)
print (ccftable)
write.csv(ccftable, file = "CCF_NO3vsSnowDepth_Stats.csv")
}
}
此外,您应该在循环结束时编写csv表,而不是在每一行。