Alexander.Herr at csiro.au
2007-Aug-31 05:23 UTC
[R] FW: sapply to return factors in dataframe
Ahhrg List, there was a hitch in the previous code. Updated and functional version follows after my initial question: I am trying to randomise a dataframe with mixed factors/numeric variables and return a new (randomised) dataframe with the same columns (as factors/numeric). simgap<-function(x) { ma<-max(x) mi<-min(x) Xout<-runif(length(x),min=mi,max=ma) return(Xout) } rdize.dta<-function(x){ if(is.factor(x)) { cat(str(x),"\n") factor(as.character(round(runif(n=length(x),min=1,max=nlevels(x)),0)))} else if(is.integer(x)) round(simgap(x),0) else if(is.numeric(x)) simgap(x) else x<-c("Error, not factor/numeric") return(x) } sapply(warpbreaks,FUN=function(x) rdize.dta(x))->test str(test) While I could to this in a loop, I am unable to do this with sapply. Any suggestions? Thanks Herry Dr Alexander Herr - Herry Spatial and statistical analyst CSIRO, Sustainable Ecosystems Davies Laboratory, University Drive, Douglas, QLD 4814 Private Mail Bag, Aitkenvale, QLD 4814 Phone/www (07) 4753 8510; 4753 8650(fax) Home: http://herry.ausbats.org.au Webadmin ABS: http://ausbats.org.au Sustainable Ecosystems: http://www.cse.csiro.au/ -------------------------------------------- -----Original Message----- From: Herr, Alexander Herr - Herry (CSE, Townsville) Sent: Friday, August 31, 2007 2:50 PM To: 'r-help at stat.math.ethz.ch' Subject: sapply to return factors in dataframe Hi List, I am trying to randomise a dataframe with mixed factors/numeric variables and return a new (randomised) dataframe with the same columns (as factors/numeric). simgap<-function(x) { ma<-max(x) mi<-min(x) Xout<-runif(length(x),min=mi,max=ma) return(Xout) } rdize.dta<-function(x){ if(is.factor(x)) { cat(str(x),"\n") factor(as.character(round(runif(n=length(x),min=1,max=nlevels(xx)),0)))} else if(is.integer(x)) round(simgap(x),0) else if(is.numeric(x)) simgap(x) else x<-c("Error, not factor/numeric") return(x) } sapply(warpbreaks,FUN=function(x) rdize.dta(x))->test str(test) While I could to this in a loop, I am unable to do this with sapply. Any suggestions? Thanks Herry