英文:
How to seperate a big tibble into several samll tibbles by specify a serious of columns
问题
分离一个大的tibble,通过在tidyverse
中的select
指定一系列列,我在如何使用map*
进行迭代并将它们存储在环境中方面遇到了问题,有什么好的想法吗?
library(tidyverse)
# 创建一个tibble
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]
)
## 假设要组合的列
grA <- c("col1", "col2")
grB <- c("col3", "col4")
grC <- c("col5", "col6")
cols_list <- list(grA, grB, grC)
## 通过select获取一个tibble:
result <- my_tibble %>% select(cols_list[[1]])
## 但如何使用map*(而不是baseR)和将其存储在不同对象中?
result_list <- my_tibble %>% map(~select(.x, !!!cols_list))
非常感谢!
英文:
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!
答案1
得分: 2
library(purrr)
library(dplyr)
map(cols_list, ~ select(my_tibble, all_of(.x)))
在基础的R中,你可以使用 split.default
函数:
cols_list <- stack(lst(grA, grB, grC))
split.default(my_tibble, cols_list$ind[match(names(my_tibble), cols_list$values)])
英文:
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)])
答案2
得分: 2
使用 lapply
简单地,
lapply(cols_list, \(i) my_tibble[i])
英文:
Simply using lapply
,
lapply(cols_list, \(i) my_tibble[i])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论