Section 17 Vector Operation: NA

Operation with NA cannot be decided, so the result is NA

17.1 Missing values: Operation


Many functions will return NA if a numeric vector includes NA

Most functions can include na.rm=TRUE for removing NA values prior to applying the function.


17.2 Elementwise operation on a vector with NA

x <- c(0, 2, NA, 6)
x+5
x-5
x*4
x/2
x^2
-x
x > 3
mean(x)
sum(x==NA)  # Not the way to count NA
sum(is.na(x))

17.3 Both vectors are of the same length

x <- c(0, 2, NA, 6, 7, 5)
y <- c(NA, -2, 7, 9, 8, 7)
mean(x)
mean(y)
mean(x, na.rm=TRUE)
mean(y, na.rm=TRUE)
cor(x,y)
cor(x,y, use = 'complete.obs')

17.4 The longer vector is a multiple of the shorter vector

x <- c(0, 2, NA, 6)
y <- c(4, -2)
cor(x,y)

17.5 The longer vector is NOT a multiple of the shorter vector

# Operations on vectors of different length
x <- c(0, 2, NA, 6)
y <- c(4, -2, 7)
cor(x,y)

17.6 Numeric vector with Functions

Note that many functions will return NA if a numeric vector includes NA and you call a function without excluding NA explicitly.

x <- c(1, 2, NA, 10, 3)
sum(x)
mean(x)
sum(x, na.rm = TRUE)
mean(x, na.rm = TRUE)
mean(na.omit(x))
sqrt(x)

y <- c(1, 2, NaN, NA, 4)
sum(y)
mean(y)
sum(y, na.rm = TRUE)
mean(y, na.rm = TRUE)


x
y
x + y
x - y
x * y
x/y


17.7 Logical vector with Function

x <- c(T, F, NA, TRUE, FALSE)
sum(x)
sum(x, na.rm = TRUE)

y <- c(T, F, NaN, NA, TRUE, FALSE)
sum(y)
sum(y, na.rm = TRUE)