Reputation: 1
I want to get the differences for consecutive factors in a vector (or a column of a dataframe). But I have to ignore NA values for this operation.
difference <- abs(vector[i] - vector[i+1])
If the values of vector[i] or vector[i+1] is NA, the above operation should be ignored.
I need your help.
Upvotes: 0
Views: 38
Reputation: 11
You can use the inbuilt diff
function in R
to first compute the differences. This will return a vector containing some NA
values (corresponding to the NA
's in x
). You can then remove them leaving a vector containing only the non-NA
values.
# make a vector with some NA values
x = rnorm(100)
x[sample(c(T, F), 100, prob = c(0.05, 0.95), replace=T)] = NA
# compute differences and take absolute value
d = abs(diff(x))
# remove na values
d2 = d[!is.na(d)]
Upvotes: 1