On 05/29/2010 02:30 AM, UM wrote:

hi,
I have been trying to do this in R (have implemented it in Excel) but I have
been using a very inefficent way (loops etc.). I have matrix A (columns are
years and ages are rows)  and matrix B (columns are birth yrs and rows are
ages)


I would like to first turn matrix A into matrix B

And then I would like to convert matrix B back again to the original matrix
A. (I have left out details of steps) but this is the gist of what I want to
do. Can anyone please give any insights?


Hi UM,
The answer is somewhat trivial (see below) but my initial misunderstanding of the question led me to write a function that I have often wanted. When using an "apply" family function, I sometimes want to apply a different argument to each slice of the object. I'm pretty sure that this has been done before, and I even looked through the "plyr" package but couldn't find what I wanted. Here's an example for a data frame.

dfapply2<-function(x,FUN,args) {
 dimx<-dim(x)
 newx<-list()
 for(column in 1:dimx[2])
  newx[[column]]<-do.call(FUN,list(x[column],args[column]))
 names(newx)<-names(x)
 return(as.data.frame(newx))
}

Pretty rough, but it does apply the arguments in "args" to the respective columns. So, thanks for motivating me to program this.

Jim

digahole<-function(x) {
 dimx<-dim(x)
 years<-as.numeric(colnames(x))
 ages<-as.numeric(rownames(x))
 minby<-min(years)-max(ages)
 maxby<-max(years)-min(ages)
 newx<-matrix(NA,nrow=dimx[1],ncol=1+maxby-minby)
 rownames(newx)<-rownames(x)
 colnames(newx)<-minby:maxby
 oldrow<-rep(1:dimx[1],each=dimx[2])
 oldcol<-rep(1:dimx[2],dimx[1])
 newcol<-oldcol+rep(max(ages)-ages,each=dimx[1])
 for(element in 1:length(oldrow))
  newx[oldrow[element],newcol[element]]<-x[oldrow[element],oldcol[element]]
 return(newx)
}

fillitup<-function(x) {
 dimx<-dim(x)
 byears<-as.numeric(colnames(x))
 ages<-as.numeric(rownames(x))
 minyr<-min(byears)+max(ages)
 maxyr<-max(byears)+min(ages)
 oldx<-matrix(NA,nrow=dimx[1],ncol=1+maxyr-minyr)
 rownames<-rownames(x)
 colnames<-minyr:maxyr
 for(row in 1:dimx[1]) oldx[row,]<-x[row,which(!is.na(x[row,]))]
 return(oldx)
}

fillitup(digahole(A))

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to