stackinator
stackinator

Reputation: 5819

convert R list to tibble() - purrr or better option?

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)

What's the best way to convert the list above into a tibble? purrr maybe? I am actually going to use this list inside of a mutate call, to add said list as a column to another tibble.

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

Upvotes: 0

Views: 4223

Answers (2)

hrbrmstr
hrbrmstr

Reputation: 78802

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

Upvotes: 1

Henry Cyranka
Henry Cyranka

Reputation: 3060

I would use a combination of tibble and unlist. This way:

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))

Upvotes: 1

Related Questions