简体   繁体   中英

finding difference of 2 vectors at different place values in r

I have 2 columns let'say A and B and I want to calculate difference between them in such a way that

A[i+1] - B[i] for i = 1,2,...n

I have been trying diff function but no luck. my data is as follows

A <- c(25,35,45,50,71,89)
B <- c(15, NA, NA, NA, 21,11)

the output I want is as below

C
- (first value should be left blank)
20
NA
NA
NA
68

I tried the following code

diff <- diff(A[i+1],B[i], lag=1)

can somebody help ?

You can do like this

A <- c(25,35,45,50,71,89)
B <- c(15, NA, NA, NA, 21,11)

A[2:length(A)] - B[1:length(B)-1]

[1] 20 NA NA NA 68

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