Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

r - How to subtract value from previous observation ID?

I am working with a weird data frame where the observations are out of order, and the unique identifiers for each observation are not numbered in a linear, straightforward manner. Provided in the data set is a unique identifier ObservationID which uniquely identifies the observation, as well as PreviousObsId, which identifies the previous observation before it. I would like to subtract the value of the previous observation from the value of any given observation. How can I do this given that the data set is out of order?

So I want this:

ObservationID      PreviousObsID       Value 
256A                  866D              200
611A                  8166Q             415
866D                  611A              175
8166Q                  -                450                 

To become this:

ObservationID      PreviousObsID       Value      ValueLessPrevious
256A                  866D              200            25
611A                  8166Q             415           -35
866D                  611A              175           -240
8166Q                 -                 450           

I hope that makes sense--thanks in advance.

Data:

structure(list(ObservationID = c("256A", "611A", "866D", "8166Q"
), PreviousObsID = c("866D", "8166Q", "611A", "-"), Value = c(200L, 
415L, 175L, 450L)), class = "data.frame", row.names = c(NA, -4L
))
question from:https://stackoverflow.com/questions/65862261/how-to-subtract-value-from-previous-observation-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another option is match

df1$ValueLessPrevious <- with(df1, Value - 
          Value[match(PreviousObsID, ObservationID)])
df1$ValueLessPrevious
#[1]   25  -35 -240   NA

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...