typestar

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

  1. The delim and names arguments do the work.
  2. too_few and too_many decide what happens to odd rows.
  3. unite pastes columns together with a separator.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Splitting columns, step 4 of 12 in Reshaping & reading.

← Previous Next →