group_split: Split data.frame by groups

View source: R/group_split.R

group_splitR Documentation

Split data.frame by groups

Description

group_split() works like base::split() but

  • it uses the grouping structure from group_by() and is therefore subject to the data mask

  • it does not name the elements of the list based on the grouping as this typically loses information and is confusing

Usage

group_split(.data, ..., .keep = TRUE)

group_keys(.data)

Arguments

.data

A data.frame.

...

Grouping specification, forwarded to group_by().

.keep

logical(1). Should the grouping columns be kept (default: TRUE)?

Details

Grouped data.frames:

The primary use case for group_split() is with already groups data.frames, typically a result of group_by(). In this case, group_split() only uses the first argument, the grouped data.frame, and warns when ... is used.

Because some of these groups may be empty, it is best paired with group_keys() which identifies the representatives of each grouping variable for the group.

Ungrouped data.frames:

When used on ungrouped data.frames, group_split() forwards the ... to group_by() before the split, therefore the ... are subject to the data mask.

Value

  • group_split() returns a list of data.frames. Each data.frame contains the rows of .data with the associated group and all the columns, including the grouping variables.

  • group_keys() returns a data.frame with one row per group, and one column per grouping variable

See Also

group_by()

Examples

# Grouped data.frames:
mtcars %>% group_by(cyl, am) %>% group_split()
mtcars %>% group_by(cyl, am) %>% group_split(.keep = FALSE)
mtcars %>% group_by(cyl, am) %>% group_keys()

# Ungrouped data.frames:
mtcars %>% group_split(am, cyl)


poorman documentation built on Nov. 2, 2023, 5:27 p.m.