mapdf {dynutils} | R Documentation |
Apply a function to each row of a data frame
Description
The mapdf functions transform their input by applying a function to each row of a data frame and returning a vector the same length as the input.
These functions work a lot like purrr's map()
functions.
Usage
mapdf(.x, .f, ...)
mapdf_lgl(.x, .f, ...)
mapdf_chr(.x, .f, ...)
mapdf_int(.x, .f, ...)
mapdf_dbl(.x, .f, ...)
mapdf_dfr(.x, .f, ...)
mapdf_dfc(.x, .f, ...)
mapdf_lat(.x, .f, ...)
walkdf(.x, .f, ...)
Arguments
.x |
A data.frame, data_frame, or tibble. |
.f |
A function or formula.
If a function, the first argument will be the row as a list.
If a formula, e.g. |
... |
Additional arguments passed on to the mapped function. |
Details
-
mapdf()
always returns a list. -
mapdf_lgl()
,mapdf_int()
,mapdf_dbl()
andmapdf_chr()
return vectors of the corresponding type (or die trying). -
mapdf_dfr()
andmapdf_dfc()
return data frames created by row-binding and column-binding respectively. They require dplyr to be installed. -
mapdf_lat()
returns a tibble by transforming outputted lists to a tibble using list_as_tibble. -
walkdf()
calls .f for its side-effect and returns the input .x.
Examples
library(dplyr)
tib <- tibble(
a = c(1, 2),
b = list(log10, sqrt),
c = c("parrot", "quest"),
.object_class = list(c("myobject", "list"), c("yourobject", "list"))
)
# map over the rows using a function
tib %>% mapdf(class)
# or use an anonymous function
tib %>% mapdf(function(row) paste0(row$b(row$a), "_", row$c))
# or a formula
tib %>% mapdf(~ .$b)
# there are many more variations available
# see ?mapdf for more info
tib %>% mapdf_lgl(~ .$a > 1)
tib %>% mapdf_chr(~ paste0("~", .$c, "~"))
tib %>% mapdf_int(~ nchar(.$c))
tib %>% mapdf_dbl(~ .$a * 1.234)