The problem is the NAs in the data - you need to keep them in until you've paired up the observations, but themn tell cor()
and cor.test()
what to do with the NA data - slightly confusingly they both have different ways of specifying that the NAs should be removed.
Does this work for your dataset now?
d <- read.csv("a.csv", header = TRUE, sep = ",")
#d <- na.omit(d) #keep NAs for the moment
for(m in c("jan","feb","mar","apr","may","jun")) {
ndvi<-d$ndvi[d$month=="aug"]
precip<-d$precipitation[d$month==m]
r2<-cor(ndvi,precip,use="complete.obs")^2
cat("month =",m,"P=",cor.test(ndvi,precip,na.action=na.omit)$p.value,"\n")
plot(ndvi~precip,main=m,
sub=sprintf("r2=%.2f",r2))
abline(lm(ndvi~precip))
}