'how to view list item in tibble
The starwars
data set in tidyverse
.
I want to view the name of Luke's first starship.
What's the notation I need to use to access it? (I.e., what can I enter at the command prompt to get the answer?)
(And to be more generic, how would I access any list item?)
I've gotten as far as this so far:
starwars %>% select(name, starships) %>% filter(name == "Luke Skywalker")
Update: the answer that worked:
starwars %>% select(name, starships) %>% filter(name == "Luke Skywalker") %>% pull(starships) %>% .[[1]] %>% .[1]
Solution 1:[1]
There are several other methods to do it in pipeline
starwars %>% select(name, starships) %>% filter(name == "Luke Skywalker") %>% str
tibble[,2] [1 x 2] (S3: tbl_df/tbl/data.frame)
$ name : chr "Luke Skywalker"
$ starships:List of 1
..$ : chr [1:2] "X-wing" "Imperial shuttle"
OR
starwars %>% select(name, starships) %>% filter(name == "Luke Skywalker") %>% as.data.frame()
name starships
1 Luke Skywalker X-wing, Imperial shuttle
Solution 2:[2]
starwars$starships[[1]]
would return the the 1st vector.
starwars$starships[[1]]
#[1] "X-wing" "Imperial shuttle"
You can subset further -
starwars$starships[[1]][1]
#[1] "X-wing"
dplyr
way -
library(dplyr)
starwars %>% select(starships) %>% pull(starships) %>% .[[1]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AnilGoyal |
Solution 2 | Ronak Shah |