Subset of vector subsets

Considering:

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 cut 18 14 

Why shining_list[[3]][3] and shining_list$reviews[3] are shining_list$reviews[3] :

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

While shining_list[[c(3,3)]] returns:

 [1] 3 

This section is about a subset of vector subsets and subsets in a DataCamp .

+5
source share
1 answer

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 

Inside, factor factors are stored as an integer vector with some structure defined above:

 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 will only have an integer representation. I think your example is one such case, several others:

 c(reviews[3], reviews[4]) ## [1] 3 4 ifelse(TRUE, reviews[1], reviews[2]) ## [1] 3 
+4
source

Source: https://habr.com/ru/post/1232010/


All Articles