为多个列表元素分配名称的函数

Function to assign names to multiple list elements

我有一个数据帧列表 int1int2。此代码的最终目标是将名称分配给 int1int2 中的元素。我工作的其余工作流程需要我多次命名列表的元素,我想知道如何创建一个函数来使用 base r 函数减少击键次数。有什么想法吗?

library(lubridate)
library(tidyverse)
library(purrr)

date <- rep_len(seq(dmy("01-01-2011"), dmy("31-07-2011"), by = "days"), 200)
ID <- rep(c("A","B", "C"), 200)
df <- data.frame(date = date,
                 x = runif(length(date), min = 60000, max = 80000),
                 y = runif(length(date), min = 800000, max = 900000),
                 ID)

df$Month <- month(df$date)

# Create first list
int1 <- df %>%
  # arrange(ID) %>%   # skipped for readability of result
  mutate(new = floor_date(date, '10 day')) %>%
  mutate(new = if_else(day(new) == 31, new - days(10), new)) %>% 
  group_by(ID, new) %>%
  filter(Month == "1") %>% 
  group_split()

# Create second list
int2 <- df %>%
  # arrange(ID) %>%   # skipped for readability of result
  mutate(new = floor_date(date, '10 day')) %>%
  mutate(new = if_else(day(new) == 31, new - days(10), new)) %>% 
  group_by(ID, new) %>%
  filter(Month == "2") %>% 
  group_split()

# Expected Output

# Assign names to int1
names(int1) <- sapply(int1, function(x) paste(x$ID[1],
                                              x$new[1], sep = "_"))
# Assign names to int2
names(int2) <- sapply(int2, function(x) paste(x$ID[1],
                                              x$new[1], sep = "_"))

使用 group_split 不会命名 list 元素。它在 ?group_split

中指定

it does not name the elements of the list based on the grouping as this typically loses information and is confusing.

而是使用 base R 中的 split,这将 return 的名称 paste 使用 'ID' 中的 .,'new' 列

int1 <- df %>%
  # arrange(ID) %>%   # skipped for readability of result
  mutate(new = floor_date(date, '10 day')) %>%
  mutate(new = if_else(day(new) == 31, new - days(10), new)) %>% 
  group_by(ID, new) %>%
  filter(Month == "1") %>% ungroup %>% 
  {split(., .[c('ID', 'new')])}

同样适用于 int2