鉴于:
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
为什么shining_list[[3]][3]
和shining_list$reviews[3]
会返回:
[1] Good
Levels: Bad < OK < Good < Perfect
shining_list[[c(3,3)]]
返回:
[1] 3
这是关于DataCamp的向量子集与列表子集的部分。
答案 0 :(得分:4)
这很可能是因为因素不是载体:
reviews <- factor(c("Good", "OK", "Good", "Perfect", "Bad", "Perfect", "Good"),
levels=c("Bad", "OK", "Good", "Perfect"), ordered=TRUE)
is.vector(reviews)
## [1] FALSE
在内部,因子级别存储为整数向量,其顶部定义了一些结构:
unclass(reviews)
## [1] 3 2 3 4 1 4 3
## attr(,"levels")
## [1] "Bad" "OK" "Good" "Perfect"
在某些情况下,此结构会崩溃,而您只剩下整数表示。我认为你的例子就是其中一个例子,其他几个是:
c(reviews[3], reviews[4])
## [1] 3 4
ifelse(TRUE, reviews[1], reviews[2])
## [1] 3