Learn R Programming

purrr (version 0.1.0)

by_row: Apply a function to each row of a data frame

Description

Applies ..f to each row of .d. By default, the whole row is appended to the result to serve as identifier (set .labels to FALSE to prevent this). In addition, if ..f returns a multi-rows data frame or a non-scalar atomic vector, a .row column is appended to identify the row number in the original data frame. If ..f's output is not a data frame nor an atomic vector, a list-column is created. In all cases, by_row() and map_row() create a data frame in tidy format.

Usage

by_row(.d, ..f, ..., .labels = TRUE)

map_rows(.d, .f, ..., .labels = TRUE)

Arguments

.d
A sliced data frame.
...
Further arguments passed to ..f.
.labels
If TRUE, the returned data frame is prepended with the labels of the slices (the columns in .d used to define the slices). They are recycled to match the output size in each slice if necessary.
.f,..f
A function to apply to each row. If ..f does not return a data frame or an atomic vector, a list-column is created under the name .out. If it returns a data frame, it should have the same number of rows within groups and the same

Value

  • A data frame.

Details

map_rows() is intended to provide a version of map_n() that works better with data frames. The distinction between by_row() and map_rows() is that the former passes a data frame to ..f while the latter maps the columns to its function call. This is essentially like using map_call() with each row of a data frame. Another way to view this is that map_row() is equivalent to using by_row() with a function lifted to accept dots (see lift_ld()).

See Also

by_slice()

Examples

Run this code
# ..f should be able to work with a list or a data frame. As it
# happens, sum() handles data frame so the following works:
mtcars %>% by_row(sum)

# Other functions such as mean() may need to be adjusted with one
# of the lift_xy() helpers:
mtcars %>% by_row(lift_vl(mean))

# To run a function with map_rows(), make sure it is variadic (that
# it accepts dots)
mtcars %>% map_rows(sum)
mtcars %>% map_rows(lift_vd(mean))

Run the code above in your browser using DataLab