代码之家  ›  专栏  ›  技术社区  ›  stackinator Brenton Wiernik

将R list转换为tible()-purrr或更好的选项?

  •  0
  • stackinator Brenton Wiernik  · 技术社区  · 7 年前
    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)
    

    将上面的列表转换为tible的最佳方法是什么?也许是呼噜声?实际上,我将在一个mutate调用中使用这个列表,将所述列表作为一列添加到另一个tible中。

    # A tibble: 100 x 1
        grp
      <dbl>
    1     1
    2     1
    3     1
    4     1
    etc...
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   hrbrmstr    7 年前

    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
    
        2
  •  1
  •   Henry Cyranka    7 年前

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