Learn R Programming

tidytable (version 0.8.0)

extract.: Extract a character column into multiple columns using regex

Description

Given a regular expression with capturing groups, extract() turns each group into a new column. If the groups don't match, or the input is NA, the output will be NA. When you pass same name in the into argument it will merge the groups together. Whilst passing NA in the into arg will drop the group from the resulting tidytable

Usage

extract.(
  .df,
  col,
  into,
  regex = "([[:alnum:]]+)",
  remove = TRUE,
  convert = FALSE,
  ...
)

Arguments

.df

A data.table or data.frame

col

Column to extract from

into

New column names to split into. A character vector.

regex

A regular expression to extract the desired values. There should be one group (defined by ()) for each element of into

remove

If TRUE, remove the input column from the output data.table

convert

If TRUE, runs type.convert() on the resulting column. Useful if the resulting column should be type integer/double.

...

Additional arguments passed on to methods.

Examples

Run this code
df <- data.table(x = c(NA, "a-b-1", "a-d-3", "b-c-2", "d-e-7"))
df %>% extract.(x, "A")
df %>% extract.(x, c("A", "B"), "([[:alnum:]]+)-([[:alnum:]]+)")

# If no match, NA:
df %>% extract.(x, c("A", "B"), "([a-d]+)-([a-d]+)")
# drop columns by passing NA
df %>% extract.(x, c("A", NA, "B"), "([a-d]+)-([a-d]+)-(\\d+)")
# merge groups by passing same name
df %>% extract.(x, c("A", "B", "A"), "([a-d]+)-([a-d]+)-(\\d+)")

Run the code above in your browser using DataLab