簡體   English   中英

如何使用 dplyr 變異從將一列輸入到返回列表的 function 中創建新列?

[英]How to use dplyr mutate to create new columns from inputting one column into a function that returns a list?

我知道標題是拗口的。 我有一個返回列表的 function。 我想使用 dplyr 變異將每個值通過 function 放入列中,並將列表中的項目返回到新列中。

我的例子:

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

我可以讓 function 返回 dataframe,但我想我會遇到同樣的問題。

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)

在這里,我們可以選擇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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM