Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does expand.grid ignore options?

Tags:

r

I'm having a problem with expand.grid. It seems to be ignoring options I set at the top of my script.

For exmaple:

options(stringsAsFactors = FALSE)
tmp <- expand.grid(x = letters, y = 1:10)

returns:

> str(tmp)
'data.frame':   260 obs. of  2 variables:
 $ x: Factor w/ 26 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ y: int  1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, "out.attrs")=List of 2
  ..$ dim     : Named int  26 10
  .. ..- attr(*, "names")= chr  "x" "y"
  ..$ dimnames:List of 2
  .. ..$ x: chr  "x=a" "x=b" "x=c" "x=d" ...
  .. ..$ y: chr  "y= 1" "y= 2" "y= 3" "y= 4" ...

What am I doing wrong?

like image 350
rrs Avatar asked Jun 04 '14 22:06

rrs


2 Answers

This is because expand.grid's function argument default is set to TRUE. If you just type ?expand.grid or head(expand.grid) from an R session, you'll see the function definition to be:

> head(expand.grid)

1 function (..., KEEP.OUT.ATTRS = TRUE, stringsAsFactors = TRUE) 
2 {                                                              
3     nargs <- length(args <- list(...))                         
4     if (!nargs)                                                
5         return(as.data.frame(list()))                          
6     if (nargs == 1L && is.list(a1 <- args[[1L]]))

And this is different from the default value provided to read.table(), for example:

> head(read.table)
1 function (file, header = FALSE, sep = "", quote = "\\"'", dec = ".",        
2     row.names, col.names, as.is = !stringsAsFactors, na.strings = "NA",     
3     colClasses = NA, nrows = -1, skip = 0, check.names = TRUE,              
4     fill = !blank.lines.skip, strip.white = FALSE, blank.lines.skip = TRUE, 
5     comment.char = "#", allowEscapes = FALSE, flush = FALSE,                
6     stringsAsFactors = default.stringsAsFactors(), fileEncoding = "",    

where default.stringsAsFactors() will return basically getOption("stringsAsFactors").

You'll therefore have to set it explicitly.

like image 189
Arun Avatar answered Nov 12 '22 10:11

Arun


In addition to @Arun explanation, you can wrap expand.grid :

 expand_grid <- 
   function(...,stringsAsFactors= getOption("stringsAsFactors"))
     expand.grid(...,stringsAsFactors=stringsAsFactors)

Now if you apply the new function , you get the desired type:

options(stringsAsFactors = FALSE)
tmp <- expand_grid(x = letters, y = 1:10)
str(tmp,max=1)
## 'data.frame':    260 obs. of  2 variables:
## $ x: chr  "a" "b" "c" "d" ...
## $ y: int  1 1 1 1 1 1 1 1 1 1 ...
## - attr(*, "out.attrs")=List of 2
like image 14
agstudy Avatar answered Nov 12 '22 11:11

agstudy