Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply function row by row on two adjacent rows

I have a function that requires two subsequent rows as parameters, i.e.

calc <- function(x, y){
    return(x/1.07*y)
}

where x = data[i,1] and y = data[i-1,1].
The function should be applied row by row starting at row two. I cannot find a way to pass the y as an argument. Is there any way to do this without using a for-loop?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is difficult to know without a reproducible example, but here’s a base R example:

x <- 1:10
c(NA, x[-1] / (1.07*x[-length(x)]))
#[1]  NA 1.869159 1.401869 1.246106 1.168224 1.121495 1.090343 1.068091 1.051402 1.038422

You’ll need a vector whose length is the same as the number of rows, so you need to append NA in the first value.

Or with dplyr::lag:

library(dplyr)
x / (1.07*lag(x))
#[1]  NA 1.869159 1.401869 1.246106 1.168224 1.121495 1.090343 1.068091 1.051402 1.038422

Or with data.table::shift:

library(data.table)
x / (1.07*shift(x))
#[1]  NA 1.869159 1.401869 1.246106 1.168224 1.121495 1.090343 1.068091 1.051402 1.038422
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading