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
drop_nawith no arguments drops any row with an NA.replace_natakes a value per column.fillcarries the last value down, which suits time series.
Keywords and builtins used here
ccolSumsdrop_nafilllibrarylistprintreplace_natibble
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.
Step 2 of 3 in Nesting & gaps, step 7 of 12 in Reshaping & reading.