[R] Multiple plots and postscripts using split function

Jim Lemon jim at bitwrit.com.au
Sat Aug 2 12:07:49 CEST 2014


On Sat, 2 Aug 2014 05:22:26 AM Florian Denzinger wrote:
> Thank you everyone for your help so far.
> 
> I am still working on the problem to get a merged new dataframe 
which fills
> in new rows with NA values for each year that is missing for plotting 
with
> gaps ( in the example the item BARTLEY: years 1984 to 1987 should 
be filled
> with a row containing NA values). Could someone maybe help me 
with this?

Hi Florian,
This is pretty messy, but it might do what you want:
fddf<-read.table(text="NAME,ID,YEAR,VALUE
ADAMS,885,1988,-2
ADAMS,885,1989,0
BAHIA DEL DIABLO,2665,1999,4
BAHIA DEL DIABLO,2665,2000,8
BAHIA DEL DIABLO,2665,2001,19
BAHIA DEL DIABLO,2665,2002,13
BAHIA DEL DIABLO,2665,2003,13
BARTLEY,893,1983,0
BARTLEY,893,1988,2
BARTLEY,893,1989,-1
CANADA,877,1972,-1
CLARK CPI,894,1973,-3",sep=",",header=TRUE)

fillgaps<-function(x,rangevar,fillvar,fillval=NA) {
 dimx<-dim(x)
 if(dimx[1] > 1) {
  newxrangevar<-min(x[[rangevar]]):max(x[[rangevar]])
  nrows<-length(newxrangevar)
  newx<-list()
  rangevarno<-which(names(x) %in% rangevar)
  fillvarno<-which(names(x) %in% fillvar)
  cat(rangevarno,fillvarno,"\n")
  for(xcol in 1:dimx[2]) {
   if(xcol == rangevarno) {
    newx[[xcol]]<-newxrangevar
   }
   else {
    if(xcol == fillvarno) {
     newx[[xcol]]<-rep(NA,nrows)
     newx[[xcol]][which(newxrangevar %in% x[[rangevar]])]<-x[[fillvar]]
    }
    else {
     if(is.numeric(x[1,xcol]))
      newx[[xcol]]<-rep(x[1,xcol],length.out=nrows)
     else
      newx[[xcol]]<-rep(as.character(x[1,xcol]),nrows)
    }
   }
  }
  newx<-as.data.frame(newx)
  names(newx)<-names(x)
 }
 else newx<-x
 return(newx)
}

fddfn<-levels(fddf$NAME)
for(fdvar in 1:length(fddfnames)) {
 if(fdvar == 1)
  newx<-fillgaps(fddf[fddf$NAME == fddfn[fdvar],],"YEAR","VALUE")
 else
  newx<-rbind(newx,fillgaps(fddf[fddf$NAME == 
fddfn[fdvar],],"YEAR","VALUE"))
}

Jim



More information about the R-help mailing list