[英]Indexing named list with vector in R
How would you index the second element of a vector which is stored as a value in a named list?您将如何索引作为值存储在命名列表中的向量的第二个元素?
I start with this:我从这个开始:
hi <- list("1" = c("a","b"),
"2" = c("dog","cat"),
"3" = c("sister","brother")
)
and would like to end up with a named list with the key plus the 2nd element of the vector ie:并希望以带有键加上向量的第二个元素的命名列表结束,即:
list("1" = "b",
"2" = "cat",
"3" = "brother"
)
You can do:你可以做:
lapply(hi, `[`, 2)
$`1`
[1] "b"
$`2`
[1] "cat"
$`3`
[1] "brother"
We can use map
我们可以使用map
library(purrr)
map(hi, pluck, 2)
#$`1`
#[1] "b"
#$`2`
#[1] "cat"
#$`3`
#[1] "brother"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.