如果我们知道嵌套层次,可以使用map_depth
library(purrr)
mydf$username <- map_depth(mydf$nestedlist, 2, pluck, "username")
-输出
> mydf
Column1 column2 nestedlist username
1 A a test, uninteresting content, test2, uninteresting content test, test2
2 B b test, uninteresting content, test2, uninteresting content test, test2
3 C c test, uninteresting content, test2, uninteresting content test, test2
或者如果不知道,则使用带有condition 检查的递归函数来查找“用户名”
library(rrapply)
mydf$username <- rrapply(mydf$nestedlist,
condition = function(x, .xname) .xname %in% 'username', how = 'prune')
> mydf
Column1 column2 nestedlist username
1 A a test, uninteresting content, test2, uninteresting content test, test2
2 B b test, uninteresting content, test2, uninteresting content test, test2
3 C c test, uninteresting content, test2, uninteresting content test, test2
如果我们想paste他们,请使用
library(stringr)
library(dplyr)
mydf$username <- rrapply(mydf$nestedlist,
condition = function(x, .xname) .xname %in% 'username',
how = 'bind') %>%
invoke(str_c, sep=", ", .)
mydf
Column1 column2 nestedlist username
1 A a test, uninteresting content, test2, uninteresting content test, test2
2 B b test, uninteresting content, test2, uninteresting content test, test2
3 C c test, uninteresting content, test2, uninteresting content test, test2
-结构
> str(mydf)
'data.frame': 3 obs. of 4 variables:
$ Column1 : chr "A" "B" "C"
$ column2 : chr "a" "b" "c"
$ nestedlist:List of 3
..$ :List of 2
.. ..$ 1:List of 2
.. .. ..$ username : chr "test"
.. .. ..$ uninteresting data: chr "uninteresting content"
.. ..$ 2:List of 2
.. .. ..$ username : chr "test2"
.. .. ..$ uninteresting data: chr "uninteresting content"
..$ :List of 2
.. ..$ 1:List of 2
.. .. ..$ username : chr "test"
.. .. ..$ uninteresting data: chr "uninteresting content"
.. ..$ 2:List of 2
.. .. ..$ username : chr "test2"
.. .. ..$ uninteresting data: chr "uninteresting content"
..$ :List of 2
.. ..$ 1:List of 2
.. .. ..$ username : chr "test"
.. .. ..$ uninteresting data: chr "uninteresting content"
.. ..$ 2:List of 2
.. .. ..$ username : chr "test2"
.. .. ..$ uninteresting data: chr "uninteresting content"
$ username : chr "test, test2" "test, test2" "test, test2"