Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用包含嵌套列表的名称中的值在数据框中创建新的标识符列_R - Fatal编程技术网

R 使用包含嵌套列表的名称中的值在数据框中创建新的标识符列

R 使用包含嵌套列表的名称中的值在数据框中创建新的标识符列,r,R,我想在每个数据帧中创建一个新的标识符列,其中包含嵌套列表名称中的值 parent <- list( a = list( foo = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)), bar = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)), puppy = data.frame(first = c(1, 2, 3), second = c(4, 5, 6))),

我想在每个数据帧中创建一个新的标识符列,其中包含嵌套列表名称中的值

parent <- list(
 a = list(
   foo = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
 bar = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
 puppy = data.frame(first = c(1, 2, 3), second = c(4, 5, 6))),
 b = list(
 foo = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
 bar = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
 puppy = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)))) 
列表b中的第一个数据帧如下所示:

 > foo
    first second identifier
 1     1      4          a
 2     2      5          a
 3     3      6          a
 >foo   
    first second identifier
 1     1      4          b
 2     2      5          b
 3     3      6          b

看起来你可能想要这样的东西

Map(function(name, list) {
  lapply(list, function(x) cbind(x, identifier=name))
}, names(parent), parent)

这里我们使用
Map()
并将列表和列表的名称以及
cbind
这些标识符放入data.frames。

我们可以使用
tidyverse
。使用
imap
循环浏览
列表
(提供
以及
键(
列表的
名称
)作为
.x
.y
,然后使用
map2
,循环遍历data.frame和
mutate的内部
列表
,创建列的标识符为
.y
又名
列表的
名称

library(tidyverse)
imap(parent, ~ map2(.x, .y, ~ .x %>%
                             mutate(identifier = .y)))
#$a
#$a$foo
#  first second identifier
#1     1      4          a
#2     2      5          a
#3     3      6          a

#$a$bar
#  first second identifier
#1     1      4          a
#2     2      5          a
#3     3      6          a

#$a$puppy
#  first second identifier
#1     1      4          a
#2     2      5          a
#3     3      6          a


#$b
#$b$foo
#  first second identifier
#1     1      4          b
#2     2      5          b
#3     3      6          b

#$b$bar
#  first second identifier
#1     1      4          b
#2     2      5          b
#3     3      6          b

#$b$puppy
#  first second identifier
#1     1      4          b
#2     2      5          b
#3     3      6          b

如果我们想让列基于data.frame名称,只使用
map
循环通过
list
元素,然后使用
imap
循环通过内部
列表
,以获得
s(
内部
列表
名称
),并创建一个新的列标识符

map(parent, ~ imap(.x,  ~ .x %>%
                       mutate(identifier = .y)))

您的解决方案将如何更改为添加一个具有数据帧名称值的列?我是tidyverse的新手。@Srizza更新了答案。我希望这就是您想要的。是的,您的解决方案很棒。我只是想进一步了解它的工作原理。