mergeNA: Merge variables with missingness

Description Usage Arguments Details Value See Also Examples

View source: R/mergeNA.R

Description

Merge multiple variables with mutually exclusive missingness

Usage

1
mergeNA(..., .factors = c("character", "numeric"))

Arguments

...

Two or more vectors of equal length, which are to be combined into one new vector. If any two vectors have non-NA values at the same index, the function will report an error.

.factors

A character string specifying whether to coerce factors in ... to “character” (i.e., their level labels), which is the default, or “numeric” (the underlying integer factor levels). This may affect the return value of the function.

Details

This is a wrapper around unbranch with the specified arguments: .ignore = NA, .fill = NA. This is useful when, for example, a survey involves two forms, with each form coded as separate variables that need to be merged together or in an experimental dataset where a single outcome measure is stored in a separate variable for each experimental condition.

Value

A vector of length equal to the inputs, with missing values replaced when available in any other vector. If all vectors are NA at a given index, the result at that index remains NA.

See Also

unbranch

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# basic examples
x <- c(NA,2,3,NA,NA,6,NA,NA,NA,10)
y <- c(NA,NA,NA,14,NA,NA,17,18,19,NA)
z <- c(NA,NA,NA,NA,25,NA,NA,NA,NA,NA)
mergeNA(x,y)
mergeNA(x,z)
mergeNA(x,y,z)

# mergeNA and unbranch equivalent)
identical(mergeNA(x,y,z),
          unbranch(x,y,z, .ignore = NA, .fill = NA))

## Not run: 
  # non-mutually exclusive missingness
  w <- c(NA,42,43,NA,25,NA,NA,NA,NA,NA)
  mergeNA(x,w) 

## End(Not run)

# treat factors as character
mergeNA(c(1,NA,NA,NA), factor(c(NA,'a','b',NA)))
mergeNA(c(1,NA,NA,NA), factor(c(NA,'a','b',NA)), .factors = "character")
# treat factors as numeric
mergeNA(c(1,NA,NA,NA), factor(c(NA,'a','b',NA)), .factors = "numeric")

leeper/mcode documentation built on May 21, 2019, 12:37 a.m.