tests/testthat/test_replace_along.R

context("replace_along")

xc <- c("One", "Two", "Three")
xcn <- c(NA, NA, "Three")

test_that("replace_along handles numeric indices", {
  expect_equal(replace_along(1:3, 2, 0), c(1, 0, 3))
  expect_equal(replace_along(1:3, 1:2, 0), c(0, 0, 3))
  expect_equal(replace_along(1:3, -3, 0), c(0, 0, 3))
})

test_that("replace_along handles logical indices", {
  expect_equal(replace_along(1:3, TRUE, 0), c(0, 0, 0))
  expect_equal(replace_along(1:3, FALSE, 0), 1:3)
  expect_equal(replace_along(1:3, c(T, T, F), 0), c(0, 0, 3))
})

test_that("replace_along handles regex", {
  expect_identical(replace_along(xc, "[O,o]", "-"), c("-", "-", "Three"))
  expect_identical(replace_along(xc, letters, "-"), rep("-", 3))
})

test_that("replace_along handles expressions and functions as condition", {
  expect_identical(replace_along(1:3, expression(x < 3), 0), c(0, 0, 3))
  expect_identical(replace_along(xcn, is.na, "-"), c("-", "-", "Three"))
})

test_that("replace_along handles lists", {
  expect_identical(
    replace_along(list(xc, xcn), function(x) any(is.na(x)), "-"),
    list(xc, "-"))
})

test_that("replace_along handles vector alignment / expansion", {
  expect_equal(replace_along(1:3, 4, 0), c(1, 2, 3, 0))
  expect_equal(replace_along(1:3, c(F,T,T,T), 0), c(1, 0, 0, 0))
  expect_equal(replace_along("+", -1:1 < 0, "-"), c("-", "+", "+"))
})

test_that("replace_along handles NULL", {
  expect_null(replace_along(NULL, NULL, NULL))
  expect_null(replace_along(NULL, TRUE, NULL))
  expect_equal(replace_along(NULL, 1, 1), 1)
  expect_equal(replace_along(1:2, 1, NULL), 2)
  expect_equal(replace_along(1:2, 2, NULL), 1)
  expect_identical(replace_along(NULL, 1:3, "-"), rep("-", 3))
  expect_identical(replace_along(NULL, 3, "-"), c(NA, NA, "-"))
})
avidclam/amxtra documentation built on May 17, 2019, 12:01 p.m.