Splitting and joining columns in R
separate_wider_delim splits one column into several; unite goes back.
library(tidyr)
runs <- tibble(
key = c("r/basics/3", "python/pandas/12", "sql/joins"),
tpm = c(88, 104, 79)
)
split <- separate_wider_delim(runs, key, delim = "/",
names = c("lang", "tour", "step"),
too_few = "align_start")
print(split)
print(unite(split, "path", lang, tour, step, sep = ":", na.rm = TRUE))
print(separate_wider_position(tibble(code = c("R04", "PY9")),
code, widths = c(lang = 2, n = 1)))
How it works
- The
delimandnamesarguments do the work. too_fewandtoo_manydecide what happens to odd rows.unitepastes columns together with a separator.
Keywords and builtins used here
clibraryprintseparate_wider_delimseparate_wider_positiontibbleunite
The run, in numbers
- Lines
- 15
- Characters to type
- 408
- Tokens
- 128
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 77 seconds.
Step 1 of 2 in Splitting columns, step 4 of 12 in Reshaping & reading.