# usid=212142 usid=210018#Ada MN wahpeton.ghcnd=chron #read.ghcnd=function(usid,method="uspaste"){ if(method=="uspaste") loc=file.path("ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/all",paste("42500",usid,".dly",sep=""))#no if(method=="nopaste") loc=file.path("ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/all",paste(usid,".dly",sep=""))#no test=download.file(loc,"temp.dat") fred=readLines("temp.dat") year=as.numeric(substr(fred,12,15));range(year)#1895 2007 month=as.numeric(substr(fred,16,17));range(year)#1895 2007 type0=substr(fred,18,21);unique(type0) #""PRCP" "TMAX" "TMIN" temp2=(type0=="TMAX");sum(temp2) #562 temp3=(type0=="TMIN");sum(temp3) #2526 time0=100*year+month year1<-min(year):max(year) g<-function(x,y){g<-100*x+y;g} chron<-sort(c(outer(year1,1:12,g))); chron=data.frame(chron);names(chron)="time" widths0=c(21,rep(c(5,3),31)) y=cumsum(widths0) widths0=cbind(1+c(0,y[1:(length(y)-1)]),y ) nrow(widths0) #100 widths0=widths0[seq(2,62,2),] #maxiumms x=fred[temp2] X=array(NA,dim=c(sum(temp2),31) ); X=data.frame(X) f=function(i){ f=substr(x,widths0[i,1],widths0[i,2]);f} for(i in 1:31){X[,i]=f(i)} for(i in 1:31){X[,i]=as.numeric(X[,i])} temp=(X== -9999);sum(temp);X[temp]=NA count=apply(!is.na(X),1,sum) xtime=time0[temp2] test=match(chron$time,xtime);temp=!is.na(test) chron$count_max=NA;chron$tmax=NA chron[temp,"count_max"]=count;chron[temp,"tmax"]= apply(X[test[temp],],1,mean,na.rm=TRUE) #minimums x=fred[temp3] X=array(NA,dim=c(sum(temp3),31) ); X=data.frame(X) f=function(i){ f=substr(x,widths0[i,1],widths0[i,2]);f} for(i in 1:31){X[,i]=f(i)} for(i in 1:31){X[,i]=as.numeric(X[,i])} temp=(X== -9999);sum(temp);X[temp]=NA count=apply(!is.na(X),1,sum) xtime=time0[temp3] test=match(chron$time,xtime);temp=!is.na(test) chron$count_min=NA;chron$tmin=NA chron[temp,"count_min"]=count;chron[temp,"tmin"]= apply(X[test[temp],],1,mean,na.rm=TRUE) chron[,c("tmax","tmin")]=round(chron[,c("tmax","tmin")]/10,2) #AVERAGES chron$tmean=apply(chron[,c("tmax","tmin")],1,mean) read.ghcnd=chron read.ghcnd } #source ("http://www.climateaudit.org/scripts/station/read.ghcnd.txt") #usid="051778"; test=read.ghcnd(paste("42500",usid,sep=""))