#----------------------------------------------------------------------------
# Numeric vector
num <- c(1, 3, 2, 4, 5)
# Example 1a: Replace 2 with NA
as.na(num, na = 2)
# Example 1b: Replace 2, 3, and 4 with NA
as.na(num, na = c(2, 3, 4))
# Example 1c: Replace NA with 2
na.as(c(1, 3, NA, 4, 5), na = 2)
#----------------------------------------------------------------------------
# Character vector
chr <- c("a", "b", "c", "d", "e")
# Example 2a: Replace "b" with NA
as.na(chr, na = "b")
# Example 2b: Replace "b", "c", and "d" with NA
as.na(chr, na = c("b", "c", "d"))
# Example 2c: Replace NA with "b"
na.as(c("a", NA, "c", "d", "e"), na = "b")
#----------------------------------------------------------------------------
# Factor
fac <- factor(c("a", "a", "b", "b", "c", "c"))
# Example 3a: Replace "b" with NA
as.na(fac, na = "b")
# Example 3b: Replace "b" and "c" with NA
as.na(fac, na = c("b", "c"))
# Example 3c: Replace NA with "b"
na.as(factor(c("a", "a", NA, NA, "c", "c")), na = "b")
#----------------------------------------------------------------------------
# Matrix
mat <- matrix(1:20, ncol = 4)
# Example 4a: Replace 8 with NA
as.na(mat, na = 8)
# Example 4b: Replace 8, 14, and 20 with NA
as.na(mat, na = c(8, 14, 20))
# Example 4c: Replace NA with 2
na.as(matrix(c(1, NA, 3, 4, 5, 6), ncol = 2), na = 2)
#----------------------------------------------------------------------------
# Array
# Example 5: Replace 1 and 10 with NA
as.na(array(1:20, dim = c(2, 3, 2)), na = c(1, 10))
#----------------------------------------------------------------------------
# List
# Example 6: Replace 1 with NA
as.na(list(x1 = c(1, 2, 3, 1, 2, 3), x2 = c(2, 1, 3, 2, 1)), na = 1)
#----------------------------------------------------------------------------
# Data frame
df <- data.frame(x1 = c(1, 2, 3), x2 = c(2, 1, 3), x3 = c(3, 1, 2))
# Example 7a: Replace 1 with NA
as.na(df, na = 1)
# Example 7b: Replace 1 with NA for the variable x2
as.na(df, x2, na = 1)
# Alternative specification
as.na(df$x2, na = 1)
# Example 7c: Replace 1 and 3 with NA
as.na(df, na = c(1, 3))
# Example 7d: Replace 1 with NA in 'x2' and 'x3'
as.na(df, x2, x3, na = 1)
# Example 7e: Replace NA with -99
na.as(data.frame(x1 = c(NA, 2, 3), x2 = c(2, NA, 3)), na = -99)
# Example 7f: Recode by replacing 30 with NA and then replacing NA with 3
na.as(data.frame(x1 = c(1, 2, 30), x2 = c(2, 1, 30)), na = 3, as.na = 30)
Run the code above in your browser using DataLab