Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector Subsetting vs. List Subsetting

Tags:

r

Given:

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

Why does shining_list[[3]][3]and shining_list$reviews[3] return :

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

Whereas shining_list[[c(3,3)]] return :

[1] 3

This is a section on Vector Subsetting vs. List Subsetting at DataCamp.

like image 438
sally Avatar asked Sep 26 '22 16:09

sally


1 Answers

This is most likely due to the fact that factors are not vectors:

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

Internally the factor-levels are stored as an integer vector with some structure defined on top:

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

In some cases this structure will collapse, and you are left with just the integer representation. I think that your example is one of those cases, a couple of others are:

c(reviews[3], reviews[4])
## [1] 3 4
ifelse(TRUE, reviews[1], reviews[2])
## [1] 3
like image 172
DGKarlsson Avatar answered Sep 30 '22 07:09

DGKarlsson