Re: [R] Problem with Freq function {prettyR}

From: Jim Lemon <jim_at_bitwrit.com.au>
Date: Sat, 14 Jun 2008 20:28:54 +1000

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)
}

R-help_at_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. Received on Sat 14 Jun 2008 - 10:29:43 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 14 Jun 2008 - 12:30:43 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive