I know the title is a mouthful. I have a function that returns a list. 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.
My example:
I am working on the list using the function. Inside the function, I am using the mutate which a part of dplyr package. I am using them to put each value of the column to the list using the function. and finally, the list returns the new column.
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 can use the function to return the data frame but it's happening.
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))))
}
So I made the changes as shown:
new_df <- my_df %>%
mutate_at(.vars = digits_only, .funs = compress_it_list)