2015-09-22 16 views
5

Data:Vector sottoinsiemi vs. Lista sottoinsiemi

actors_vector <- c("Jack Nicholson", "Shelley Duvall", "Danny Lloyd", 
        "Scatman Crothers", "Barry Nelson") 

reviews_factor <- factor(c("Good", "OK", "Good", "Perfect", 
          "Bad", "Perfect", "Good"), 
         levels = c("Bad", "OK", "Good", "Perfect"), 
         ordered = TRUE) 

shining_list <- list(title = "The Shining", 
        actors = actors_vector, 
        reviews = reviews_factor) 

shining_list 
$title 
[1] "The Shining" 

$actors 
[1] "Jack Nicholson" "Shelley Duvall" "Danny Lloyd"  "Scatman Crothers" 
[5] "Barry Nelson"  

$reviews 
[1] Good OK  Good Perfect Bad  Perfect Good 
Levels: Bad < OK < Good < Perfect 

$boxoffice 
       US Non-US 
First release 39  47 
Director's cut 18  14 

Perché shining_list[[3]][3] e shining_list$reviews[3] ritorno:

[1] Good 
Levels: Bad < OK < Good < Perfect 

Mentre shining_list[[c(3,3)]] ritorno:

[1] 3 

Questa è una sezione sulla Vettore Subsetting vs. List Subsetting a DataCamp.

+1

Hai un fattore nelle recensioni. Quando esegui l'estrazione con 'c (3,3)', viene convertito in un numero intero. –

+0

L'OP sta chiedendo _why_, però. È in conflitto con _ "' [['può essere applicato ricorsivamente alle liste, in modo che se l'indice singolo' i' è un vettore di lunghezza 'p',' alist [[i]] 'è equivalente a' alist [[i1 ]] '...' [[ip]] 'fornisce tutti i risultati dell'indicizzazione finale in una lista.", ma 'shining_list [[3]] [[3]]' restituisce '[1] Buono' /' evels : Bad hrbrmstr

risposta

4

Ciò è probabilmente dovuto al fatto che i fattori non sono vettori:

reviews <- factor(c("Good", "OK", "Good", "Perfect", "Bad", "Perfect", "Good"), 
        levels=c("Bad", "OK", "Good", "Perfect"), ordered=TRUE) 
is.vector(reviews) 
## [1] FALSE 

Internamente il fattore livelli sono memorizzati come un vettore intero con qualche struttura definita sopra:

unclass(reviews) 
## [1] 3 2 3 4 1 4 3 
## attr(,"levels") 
## [1] "Bad"  "OK"  "Good" "Perfect" 

In alcuni casi questa struttura collasserà e ti resterà solo la rappresentazione intera. Penso che il tuo esempio sia uno di quei casi, un paio di altri sono:

c(reviews[3], reviews[4]) 
## [1] 3 4 
ifelse(TRUE, reviews[1], reviews[2]) 
## [1] 3 
Problemi correlati