简体   繁体   中英

Getting differences between consecutive values in a column (or vector) by ignoring NA values

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.

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM