[英]How to use dplyr mutate to create new columns from inputting one column into a function that returns a list?
I know the title is a mouthful.我知道标题是拗口的。 I have a function that returns a list.
我有一个返回列表的 function。 I would like to use dplyr mutate to put each value in the column through the function and put the items in the list returned into new columns.
我想使用 dplyr 变异将每个值通过 function 放入列中,并将列表中的项目返回到新列中。
My example:我的例子:
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))))
}
I could make the function return a dataframe, but I think I'd have the same problem.我可以让 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))))
}
I was trying to figure out something in the vein of我试图弄清楚
new_df <- my_df %>%
mutate_at(.vars = digits_only, .funs = compress_it_list)
Here, we have the option of unnest_wider
在这里,我们可以选择
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.