codegoblin1996
codegoblin1996

Reputation: 302

Performing calculation between rows (observations) in your dataframe

Say I have a dataframe like this:

data = structure(list(yaw = c(1, 1, 2, 3, 5), z = c(1, 2, 3, 4, 5), 
    x = c(1, 3, 2, 2, 3)), row.names = c(NA, 5L), class = "data.frame")

And I want to perform a calculation between each row (observation) and the row before it and then save this as a new column in the dataframe (or maybe save as a new data set? For example:

newdata <- data %>%
mutate(Yaw = Row2Yaw - Row1Yaw) %>%
mutate(hypotenuse = sqrt((Row2X - Row1X)^2 + (Row2Z - Row1Z)^2) %>%
mutate(lane_deviation = sin(Yaw) * hypotenuse)

Hence this gives me a lane_deviation value for the difference between these two rows. Ideally I would want to calculate this for every observation (i.e. Row3Yaw - Row2Yaw) etc...)

Is this possible in dplyr or would I need some form of loop? Any help is appreciated!

Upvotes: 2

Views: 94

Answers (1)

Rushabh Patel
Rushabh Patel

Reputation: 2764

You can achieve this using data.table as well-

setDT(data)
data[,hypotenuse:=sqrt((lead(yaw)-yaw)*2 + (lead(yaw)-yaw)*2)]
data[,lane_deviation:=sin(yaw) * hypotenuse]

As mentioned in the comments by @David, we can use lead function

And using dplyr

newdata <- data %>%
    mutate(Yaw = lead(yaw)-yaw) %>%
    mutate(hypotenuse = sqrt((lead(yaw)-yaw)^2 + (lead(yaw)-yaw)^2)) %>%
               mutate(lane_deviation = sin(Yaw) * hypotenuse)

Upvotes: 1

Related Questions