typestar

Merging and binding in R

Combining tables by key or by stacking.

people <- data.frame(id = 1:3, name = c("ada", "grace", "kay"))
scores <- data.frame(id = c(1, 2, 4), score = c(95, 88, 70))

inner <- merge(people, scores, by = "id")
left <- merge(people, scores, by = "id", all.x = TRUE)
full <- merge(people, scores, by = "id", all = TRUE)

stacked <- rbind(people, data.frame(id = 4, name = "alan"))
widened <- cbind(people, active = c(TRUE, TRUE, FALSE))

How it works

  1. merge joins on a shared column, inner by default.
  2. all.x and all produce left and full joins.
  3. rbind stacks rows; cbind adds columns.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
392
Tokens
132
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 1 of 4 in Reshaping & combining, step 4 of 8 in Data frames in base R.

← Previous Next →