Home > Net >  Trying to find ratio of current value to previous in R
Trying to find ratio of current value to previous in R

Time:09-02

I am taking an excel file as input and want to find display the ratio of previous value to current value of each row.

Example

Input column from excel

  1. Input Output
  2. 50 2
  3. 25 2.5
  4. 10 0.5
  5. 20

What function can I use to do this?

CodePudding user response:

We could use

library(dplyr)
dat %>%
    mutate(Output = lead(lag(Input)/Input))

-output

  Input Output
1    50    2.0
2    25    2.5
3    10    0.5
4    20     NA

data

dat <- structure(list(Input = c(50, 25, 10, 20)), 
class = "data.frame", row.names = c(NA, 
-4L))
  •  Tags:  
  • r
  • Related