Skip to contents

Separate one column into multiple columns. May be slow on large data frames.

Usage

separate(
  data,
  col,
  into,
  sep = "[^[:alnum:]]+",
  remove = TRUE,
  convert = FALSE,
  extra = "error"
)

Arguments

data

A data frame.

col

A string for the column name.

into

A character vector of names for the new variables.

sep

A string to be evaluated as a regular expression for separating between columns.

remove

TRUE or FALSE. If TRUE, remove input column from the output data frame.

convert

TRUE or FALSE. If TRUE, will run type.convert() with as.is = TRUE on new columns.

extra

Specify a string to control what happens when there are too many separated values: "error" (the default) returns error. "drop" drop extra values. "merge" splits at most length(into) times.

Value

data.frame

References

Hadley Wickham and Lionel Henry (2017). tidyr: Easily Tidy Data with 'spread()' and 'gather()' Functions. R package version 0.2.0. https://CRAN.R-project.org/package=tidyr. Git commit 0cdc67ab9a4ae92ce7316dbf3f5eaf4a9afffd5b

Examples

#----------------------------------------------------------------------------
# separate() examples
#----------------------------------------------------------------------------
library(bkdat)

df <- data.frame(x = c(NA, "a.b", "a.d", "b.c"))

df
#>      x
#> 1 <NA>
#> 2  a.b
#> 3  a.d
#> 4  b.c
separate(df, "x", c("A", "B"))
#>      A    B
#> 1 <NA> <NA>
#> 2    a    b
#> 3    a    d
#> 4    b    c

# If every row doesn't split into the same number of pieces, use
# the extra and file arguments to control what happens
df <- data.frame(x = c("a", "a b", "a b c", NA))

df
#>       x
#> 1     a
#> 2   a b
#> 3 a b c
#> 4  <NA>
# this errors
#separate(df, "x", c("a", "b"), extra = "error")
# this drops
separate(df, "x", c("a", "b"), extra = "drop")
#>      a    b
#> 1    a <NA>
#> 2    a    b
#> 3    a    b
#> 4 <NA> <NA>
# this merges
separate(df, "x", c("a", "b"), extra = "merge")
#>      a    b
#> 1    a <NA>
#> 2    a    b
#> 3    a  b c
#> 4 <NA> <NA>

# again use merge to only separate once
df <- data.frame(x = c("x: 123", "y: error: 7"))

df
#>             x
#> 1      x: 123
#> 2 y: error: 7
separate(df, "x", c("key", "value"), ": ", extra = "merge")
#>   key    value
#> 1   x      123
#> 2   y error: 7