# NOT RUN {
1:5 %>%
to_list(rnorm(n = 3, .x))
# or in 'lapply' style
1:5 %>%
to_list(rnorm, n = 3) %>%
to_vec(mean)
# or use an anonymous function
1:5 %>%
to_list(function(x) rnorm(3, x))
# Use to_vec() to reduce output to a vector instead
# of a list:
# filtering - return only even numbers
to_vec(1:10, if(.x %% 2 == 0) .x)
# filtering - mean only on the numeric columns
to_vec(iris, if(is.numeric(.x)) mean(.x))
# mean for numerics, number of distincts for others
to_vec(iris, if(is.numeric(.x)) mean(.x) else uniqueN(.x))
# means for Sepal
to_vec(iris, if(startsWith(.name, "Sepal")) mean(.x))
# A more realistic example: split a data frame into pieces, fit a
# model to each piece, summarise and extract R^2
mtcars %>%
split(.$cyl) %>%
to_list(summary(lm(mpg ~ wt, data = .x))) %>%
to_vec(.x$r.squared)
# If each element of the output is a data frame, use
# to_df to row-bind them together:
mtcars %>%
split(.$cyl) %>%
to_list(lm(mpg ~ wt, data = .x)) %>%
to_df(c(cyl = .name, coef(.x)))
# }
# NOT RUN {
# read all csv files in "data" to data.frame
all_files = dir("data", pattern = "csv$", full.names = TRUE) %>%
to_df(fread,
idvalue = basename(.x),
idname = "filename",
trace = "pb"
)
# }
Run the code above in your browser using DataLab