繁体   English   中英

Dataframe 使用 purrr 为数据帧列表中的列命名

[英]Dataframe name to column in list of dataframes using 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)

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

所以它会为每个数据框看起来像:

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

然后我会将其合并到一个数据框,以便 plot。我可以通过mutate(batch = deparse(substitute(batch_1)))手动完成,但我正在努力“purrr-ifying”这个。

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

给出错误:UseMethod("mutate") 中的错误:没有适用于“mutate”的方法应用于 class“字符”的 object

它不必特定于 purrr,欢迎使用任何方法。

编辑:@user63230 解决方案有效。 但是,通常情况下,您会在已有解决方案时找到解决方案!

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

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

另一种方法是使用lst而不是list ,它会使用直接使用这些名称 ( .y ) 的imap自动为您命名列表。

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

使用baseplyr的替代答案是,

#import all batch dataframes 
df= mget(grep(pattern = "bat", x = ls(), value = TRUE))

#convert the list to dataframe
df = ldply(df, as.data.frame)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM