2014-06-04 14 views
12

Mam problem z expand.grid. Wygląda na to, że ignoruję opcje ustawione u góry mojego skryptu.Dlaczego expand.grid ignoruje opcje?

Dla exmaple:

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

powraca:

> 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" ... 

Co robię źle?

+3

Ponieważ argument jest zakodowana, zamiast ustawiać jako 'default.stringsAsFactors()'. Prawdopodobnie coś, co można by podnieść jako potencjalną zmianę, jak sądzę, jeśli masz grubą skórę. – joran

+6

'? Options' sugeruje, że' opcje (stringAsFactors = FALSE) 'będą miały wpływ tylko na' data.frame' i 'read.table':" "stringiAsFactors": Domyślne ustawienie dla argumentów "data.frame" i "read. stół'." –

Odpowiedz

15

To dlatego, że domyślny argument funkcji expand.grid jest ustawiony na TRUE. Jeśli wystarczy wpisać ?expand.grid lub head(expand.grid) z sesji R, zobaczysz definicję funkcji do:

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

I ta różni się od wartości domyślnej dostarczonych read.table(), na przykład:

> 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 = "",  

gdzie default.stringsAsFactors() zwróci w zasadzie getOption("stringsAsFactors").

Będziesz musiał ustawić to wyraźnie.

14

Oprócz @Arun wyjaśnienia, można owinąć expand.grid:

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

Teraz, jeśli zastosowanie nowej funkcji, można uzyskać pożądany typ:

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 
Powiązane problemy