Search code examples
rtidyversepurrr

How to seperate a big tibble into several samll tibbles by specify a serious of columns


To seperate a big tibble into several samll tibbles by specify a serious of columns could be acted by select in tidyverse, and I am trouble in how to use map* for iteration and store them in the environment, any good idea?

library(tidyverse)

# 
my_tibble <- tibble(
  col1 = rnorm(10),
  col2 = runif(10),
  col3 = letters[1:10],
  col4 = sample(1:100, 10, replace = TRUE),
  col5 = factor(rep(c("A", "B"), 5)),
  col6 = LETTERS[1:10]
)

## assume the combination
grA <- c("col1", "col2")
grB <- c("col3", "col4")
grC <- c("col5", "col6")
cols_list <- list(grA, grB, grC)

## I can get one tibble by select:
my_tibble %>% select(cols_list[[1]])

## but how to use select with map* (rather the baseR) and store it into different objects?
my_tibble %>% map(~select(cols_list))

Thanks so much!


Solution

  • library(purrr)
    library(dplyr)
    map(cols_list, ~ select(my_tibble, all_of(.x)))
    

    In base R, you can use split.default:

    cols_list <- stack(lst(grA, grB, grC))
    split.default(my_tibble, cols_list$ind[match(names(my_tibble), cols_list$values)])