如何在 R 中同时改变数据帧列表

How to mutate a list of dataframes simultaneously in R

我正在尝试在 R 中同时改变作为数据帧列表一部分的数据帧

这是我在数据框上 运行 的功能,这能够 mutate/group_by/summarise

ebird_tod_1 <- ebird_split[[1]] %>% #ebird_split is the df list.
  mutate(tod_bins = cut(time_observations_started, 
                        breaks = breaks, 
                        labels = labels,
                        include.lowest = TRUE),
         tod_bins = as.numeric(as.character(tod_bins))) %>% 
  group_by(tod_bins) %>% 
  summarise(n_checklists = n(),
            n_detected = sum(species_observed),
            det_freq = mean(species_observed))

这对于列表中的一个数据帧非常有效,但是我有 45 个,而且我宁愿没有这种编码的页面来创建 45 变量。因此,我正在寻找一种将“ebird_tod_1”变量增加到“ebird_tod_2”“ebird_tod_3”等的方法。同时发生修改的数据帧应该改变到“ebird_split[[2]]”“ebird_split[[3]]”。

我试过使用repeat和map功能没有成功。

我希望这就是有人需要帮助的所有信息,我是 R 的新手,

谢谢。

由于您未提供示例数据,因此未测试以下代码。但是一般的方法是将您的代码放在一个函数中并使用 lapplypurrr::map 遍历您的数据帧列表并将结果存储在列表中(而不是创建多个对象):

myfun <- function(x) {
  x %>%
    mutate(tod_bins = cut(time_observations_started, 
                          breaks = breaks, 
                          labels = labels,
                          include.lowest = TRUE),
           tod_bins = as.numeric(as.character(tod_bins))) %>% 
    group_by(tod_bins) %>% 
    summarise(n_checklists = n(),
              n_detected = sum(species_observed),
              det_freq = mean(species_observed))
  
}
ebird_tod <- lapply(ebird_split, myfun)

在您的示例中,您似乎想从 data.frames 的列表在全局环境中创建 data.frame。为此,我们可以使用 rlang::env_bind:

library(tidyverse)

# a list of data.frames
data_ls <- iris %>% 
  nest_by(Species) %>% 
  pull(data)
  
# name the list of data frames
data_ls <- set_names(data_ls, paste("iris", seq_along(data_ls), sep = "_"))

data_ls %>% 
  # use map or lapply to make some operations
  map(~ mutate(.x, new = Sepal.Length + Sepal.Width) %>% 
        summarise(across(everything(), mean),
                  n = n())) %>% 
  # pipe into env_bind and splice list of data.frames
  rlang::env_bind(.GlobalEnv, !!! .)

reprex package (v2.0.1)

创建于 2022-05-02