[R] Problem with Freq function {prettyR}
ukoenig at med.uni-marburg.de
ukoenig at med.uni-marburg.de
Sat Jun 14 12:44:51 CEST 2008
Thank you Jim,
the error message appeared, as I tried to run an example from the wonderful
script R for SAS and SPSS Users written by Bob Muenchen (p. 76):
http://oit.utk.edu/scc/RforSAS&SPSSusers.pdf
This is the code on page 76:
# Frequencies & percents using the freq function
# from the prettyR package.
freq(mydata)
Udo
Quoting Jim Lemon <jim at bitwrit.com.au>:
> ukoenig at med.uni-marburg.de wrote:
> >> ...
> >>I have a problem with freq from prettyR.
> >>
> >>Please have a look at my syntax with a litte example:
> >>
> >>
> >>library(prettyR)
> >>
> >>#Version 1
> >>test.df<-data.frame(q1=sample(1:4,8,TRUE),
> gender=sample(c("f","m"),8,TRUE))
> >>test.df
> >>freq(test.df) #No error message
> >>
> >>#Version 2
> >>test.df<-data.frame(gender=sample(c("f","m"),8,TRUE),
> q1=sample(1:4,8,TRUE))
> >>test.df
> >>freq(test.df)
> >>
> >>Error message: "Error in vector("integer", length) : Vector size can´t be
> NA"
> >>
> >>Can someone tell me, why an error message occurs in version two? I am
> >>helpless...
>
> Hi Udo,
> I'm surprised that this bug survived as long as it did. When I looked at
> the code, I immediately thought, "That's not right" and it wasn't. Here
> is the repaired function that will be in version 1.3-1.
>
> Jim
>
> freq<-function(x,variable.labels=NULL,display.na=TRUE,levels=NULL) {
>
> if(missing(x))
> stop("A vector, dataframe or matrix must be supplied")
> xdim<-dim(x)
> # get the variable label here or it might be clobbered
> if(is.null(xdim)) {
> if(is.null(variable.labels))
> variable.labels<-deparse(substitute(x))
> x<-list(x)
> nfreq<-1
> }
> else {
> nfreq<-xdim[2]
> if(is.matrix(x))
> x<-as.data.frame(x)
> if(is.null(variable.labels))
> variable.labels<-names(x)
> if(is.null(variable.labels))
> variable.labels<-paste("V",1:xdim[2],sep="",collapse="")
> }
> freq.list<-rep(list(0),nfreq)
> for(i in 1:nfreq) {
> # see if there are any NAs and if they should be displayed
> if(display.na) nna<-sum(is.na(x[[i]]))
> else nna<-0
> # tabulate barfs with NAs
> xt<-na.omit(x[[i]])
> xlevels<-levels(xt)
> if(is.null(xlevels)) xlevels<-unique(xt)
> if(is.numeric(x[[i]])) xt<-factor(xt,levels=xlevels)
> freqs<-tabulate(xt)
> categories<-xlevels
> # if NAs present, tack on a label
> if(nna) categories<-c(categories,"NA")
> # tack on the NA count
> if(nna) freqs<-c(freqs,nna)
> names(freqs)<-categories
> freq.list[[i]]<-freqs
> }
> names(freq.list)<-variable.labels
> class(freq.list)<-"freq"
> return(freq.list)
> }
>
>
More information about the R-help
mailing list