typestar

Missing values in R

drop_na, replace_na and fill: three answers to a gap.

library(tidyr)
library(dplyr)

runs <- tibble(
  lang = c("r", NA, "python", "python"),
  tpm = c(88, 96, NA, 104),
  note = c(NA, NA, "slow", NA)
)

print(drop_na(runs))
print(drop_na(runs, tpm))
print(replace_na(runs, list(lang = "unknown", tpm = 0, note = "")))
print(fill(runs, lang, .direction = "down"))
print(colSums(is.na(runs)))

How it works

  1. drop_na with no arguments drops any row with an NA.
  2. replace_na takes a value per column.
  3. fill carries the last value down, which suits time series.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
331
Tokens
119
Three-star pace
105 tpm

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

Type this snippet

Step 2 of 3 in Nesting & gaps, step 7 of 12 in Reshaping & reading.

← Previous Next →