使用 purrr 将数据框名称指定为数据框列表中的列

God*_*rim 4 r purrr

我有一个从 Excel 文件导入的数据框列表。每个文件均按其代表的批次导入并命名。

下面是一个例子:

library(tidyverse)
batch_1 <- data.frame(A = 1:3,
                      B = 4:6)
batch_2 <- data.frame(A = 1:3,
                      B = 4:6)
batch_3 <- data.frame(A = 1:3,
                      B = 4:6)
my_list <- list(batch_1, batch_2, batch_3)
Run Code Online (Sandbox Code Playgroud)

我现在想在每个数据框中创建一个新列,作为每个数据框的名称。

所以每个数据框看起来都是这样的:

  A B   batch
1 1 4 batch_1
2 2 5 batch_1
3 3 6 batch_1
Run Code Online (Sandbox Code Playgroud)

然后我将其合并到一个数据框以便绘制。我可以手动完成此操作,mutate(batch = deparse(substitute(batch_1)))但我正在努力解决“purrr-ifying”这个问题。

map(my_list, ~mutate(batch = deparse(substitute(.x))))

给出错误: UseMethod("mutate") 中的错误:没有适用于“mutate”的方法应用于类“character”的对象

它不必是特定的,任何方法都是受欢迎的。

编辑:@user63230 解决方案有效。但是,正如典型的那样,当您已经有了解决方案时,您就会找到解决方案!

这种情况的另一种解决方案是在稍后将数据帧组合成一个。

bind_rows(my_list, .id = "batch")将添加一个带有数据框名称的 id 列。

use*_*230 6

另一种方法是使用whichlst代替list自动为您命名列表,而imapwhich 直接使用这些名称 ( .y)。

library(tidyverse)
my_list <- lst(batch_1, batch_2, batch_3)
purrr::imap(my_list, ~mutate(.x, batch = .y))

# $batch_1
#   A B   batch
# 1 1 4 batch_1
# 2 2 5 batch_1
# 3 3 6 batch_1

# $batch_2
#   A B   batch
# 1 1 4 batch_2
# 2 2 5 batch_2
# 3 3 6 batch_2

# $batch_3
#   A B   batch
# 1 1 4 batch_3
# 2 2 5 batch_3
# 3 3 6 batch_3
Run Code Online (Sandbox Code Playgroud)