【问题标题】:How to use dplyr mutate to create new columns from inputting one column into a function that returns a list?如何使用 dplyr mutate 从将一列输入到返回列表的函数中创建新列?
【发布时间】:2020-04-24 00:22:32
【问题描述】:

我知道这个标题很拗口。我有一个返回列表的函数。我想使用 dplyr mutate 通过函数将每个值放入列中,并将返回的列表中的项目放入新列中。

我的例子:

library(dplyr)

my_df <- data_frame(filename = c("file1","file2","file3","file4"),
                    digits_only = c("10101010", "11011011", "10011000","11111111"))

compress_it_list <- function(txt) {
  len.raw <- sum(nchar(txt))
  len.xz <- length(memCompress(txt, "x"))
  len.gz <- length(memCompress(txt, "g"))
  len.bz2 <- length(memCompress(txt, "b"))
  return(list("len_raw" = len.raw, 
              "len_xz" = len.xz, 
              "len_gz" = len.gz, 
              "len_bz2" = len.bz2, 
              "min_compression" = min(c(len.raw, len.xz, len.gz, len.bz2))))
}

我可以让函数返回一个数据帧,但我想我会遇到同样的问题。

compress_it_df <- function(txt) {
  len.raw <- sum(nchar(txt))
  len.xz <- length(memCompress(txt, "x"))
  len.gz <- length(memCompress(txt, "g"))
  len.bz2 <- length(memCompress(txt, "b"))
  return(data_frame("len_raw" = len.raw, 
                    "len_xz" = len.xz, 
                    "len_gz" = len.gz, 
                    "len_bz2" = len.bz2, 
                    "min_compression" = min(c(len.raw, len.xz, len.gz, len.bz2))))
}

我试图弄清楚

new_df <- my_df %>%
  mutate_at(.vars = digits_only, .funs = compress_it_list)

【问题讨论】:

    标签: r list function dplyr


    【解决方案1】:

    在这里,我们可以选择unnest_wider

    library(dplyr)
    library(tidyr)
    library(purrr)
    my_df %>%
          mutate(new = map(digits_only, compress_it_list)) %>% 
          unnest_wider(c(new))
    # A tibble: 4 x 7
    #  filename digits_only len_raw len_xz len_gz len_bz2 min_compression
    #  <chr>    <chr>         <int>  <int>  <int>   <int>           <int>
    #1 file1    10101010          8     60     12      39               8
    #2 file2    11011011          8     60     13      39               8
    #3 file3    10011000          8     60     16      39               8
    #4 file4    11111111          8     64     11      39               8
    

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 2023-01-29
      相关资源
      最近更新 更多