[英]Extract the first item of the list from nested lists
I have the following column in my data table (there are more lists inside, but I just provide it simplified)我的数据表中有以下列(里面有更多列表,但我只是提供简化)
n col1
1 list(c("1", "2", "3", "5"), c("5", "6", "8", "8"))
2 list(c("9", "10", "11", "12"), c("13", "14", "15", "16"))
And I want to extract the first value from each of the lists in the row.我想从行中的每个列表中提取第一个值。 So, I want the outcome
所以,我想要结果
n col2
1 c("1", "5")
2 c("9", "13")
I looked into many examples here and on the internet about nested lists, it seems that it should be easy, but it doesn't seem that it works quite as I intend it to.我在这里和互联网上查看了许多关于嵌套列表的示例,似乎它应该很容易,但它似乎并不像我想要的那样工作。 I use the following variants of code
我使用以下代码变体
1. dt$col2 <-sapply(dt$col1 , "[[", 1)
`2. dt$col2 <- lapply(dt$col1, function(l) l[[1]])`
`3. dt$col2 <- rvest::pluck(dt$col1, 1)`
But they all give the same output which is basically the first list但是他们都给出了相同的 output 这基本上是第一个列表
n col2
1 c("1", "2", "3", "5")
2 c("9", "10", "11", "12")
There must be something wrong with my understanding, but I can't get why it happens this way我的理解一定有问题,但我不明白为什么会这样
Try:尝试:
dt$col2 <-sapply(dt$col1 , "[", 1)
(The elements of your lists are not lists, just vectors, so one bracket is fine) (列表的元素不是列表,只是向量,所以一个括号就可以了)
EDIT:编辑:
For a column inside a data.table:对于 data.table 内的列:
dt$col2 <- sapply(dt$col1,function(x){sapply(x,'[',1)})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.