[R] transpose? reshape? flipping? challenge with data frame

Carl Witthoft carl at witthoft.com
Fri Apr 23 23:20:14 CEST 2010


While the OP turned out to want to transpose his data, for those who are 
reading and would like some (ugly) code to flip a tensor about an 
arbitrary axis, here goes:
*_*  Carl


#my own cheap matrix flipflopper
flip<-function(x,flipdim=1) {
	#axis is index, so 1 is rows, 2 is cols (for matrix)
	#sanity check
	if (flipdim > length(dim(x))) stop("Dimension selected exceeds dim of 
input")
	a <-"x["
	b<-paste("dim(x)[",flipdim,"]:1",collapse="")
	d <-"]"
	# want lead and follow to be a single vector
	#now the trick: get the right number of commas
	lead<-paste(rep(',',(flipdim-1)),collapse="")
	follow <-paste(rep(',',(length(dim(x))-flipdim)),collapse="")
	thestr<-paste(a,lead,b,follow,d,collapse="")
	flipped<-eval(parse(text=thestr))
	return(invisible(flipped))
	}



More information about the R-help mailing list