如何通过指定一系列列将一个大的tibble拆分成多个小的tibbles。

huangapple go评论49阅读模式
英文:

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 &lt;- tibble(
  col1 = rnorm(10),
  col2 = runif(10),
  col3 = letters[1:10],
  col4 = sample(1:100, 10, replace = TRUE),
  col5 = factor(rep(c(&quot;A&quot;, &quot;B&quot;), 5)),
  col6 = LETTERS[1:10]
)

## assume the combination
grA &lt;- c(&quot;col1&quot;, &quot;col2&quot;)
grB &lt;- c(&quot;col3&quot;, &quot;col4&quot;)
grC &lt;- c(&quot;col5&quot;, &quot;col6&quot;)
cols_list &lt;- list(grA, grB, grC)

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

## but how to use select with map* (rather the baseR) and store it into different objects?
my_tibble %&gt;% 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 &lt;- 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 &lt;- 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])

huangapple
  • 本文由 发表于 2023年3月15日 18:16:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定