将R列表转换为tibble()-purrr或更好的选择?

时间:2018-11-04 00:03:13

标签: r dplyr purrr

library(tidyverse)
library(purrr)
x <- c(20, 30, 58)
n <- 100

mylist <- data_frame(x = c(0, x), n) %>%
  distinct() %>%
  filter(x >= 0 & x < n) %>%
  arrange(x) %>%
  bind_rows(data_frame(x = n)) %>%
  mutate(lag_x = lag(x)) %>%
  mutate(y = x - lag_x) %>%
  filter(!is.na(y)) %>%
  summarise(n = list(rep(row_number(), y))) %>%
  pull(n)

将上面的列表转换为小标题的最佳方法是什么?也许是purrr?我实际上将在mutate调用中使用此列表,以将所述列表作为列添加到另一个小标题中。

# A tibble: 100 x 1
    grp
  <dbl>
1     1
2     1
3     1
4     1
etc...

2 个答案:

答案 0 :(得分:1)

我会同时使用tibble和unlist。这样:

new_tibble <- tibble(grp = unlist(mylist))

##if you want to add it as column to a data frame, here is how I'd do it
mock_df <- tibble(x = rnorm(100),
              y = rnorm(100))

 mock_df %>% mutate(grp = unlist(mylist))

答案 1 :(得分:1)

unnest()rename()

library(tidyverse)

x <- c(20, 30, 58)
n <- 100

data_frame(x = c(0, x), n) %>%
  distinct() %>%
  filter(x >= 0 & x < n) %>%
  arrange(x) %>%
  bind_rows(data_frame(x = n)) %>%
  mutate(lag_x = lag(x)) %>%
  mutate(y = x - lag_x) %>%
  filter(!is.na(y)) %>%
  summarise(n = list(rep(row_number(), y))) %>%
  unnest(n) %>% 
  rename(grp = n)
## # A tibble: 100 x 1
##      grp
##    <int>
##  1     1
##  2     1
##  3     1
##  4     1
##  5     1
##  6     1
##  7     1
##  8     1
##  9     1
## 10     1
## # ... with 90 more rows