简体   繁体   中英

How to create a new column in R data table where each row is a function of previous row?

How to create a new column in data.table where each row is a function of previous row in R?

For example, i have the below data and function.

DT <- data.table(A = c(2,3,4,2,3,4,1,0)) 
FXN = function(x,y) {x+y}

Note: I am using x+y is an example function. In reality, the function is a bit more complicated.

I want to create a new column where the new[i] element is a FXN of( new[i-1], A[i])

I can do this using for loop as per below:

DT$new <- NA
DT$new[1]<- DT$A[1]
for (i in 2:nrow(DT) )
{
  DT$new[i] = DT$new[i-1]+DT$A[i]
}

And I get the desired output:

DT
   A new
1: 2   2
2: 3   5
3: 4   9
4: 2  11
5: 3  14
6: 4  18
7: 1  19
8: 0  19

Question is: Is there a way to do this without using for-loop? My actual function is a bit more complicated and is taking time. For example, something like:

DT[,new:= FXN(A ,lag(new,1L)) ]

But this throws up the error: Error: Input must be a vector, not a function. Run rlang::last_error() to see where the error occurred.

I ended up hacking a code using Reduce, but that is taking too much time as well.

DT$new <- Reduce(FXN, DT$A, acc=TRUE, init=0)[-1]

So I am looking for a solution with simple data.table or dplyr functions with speed in mind.

Thanks in Advance!

Similar to Reduce purrr has accumulate function which you can try:

library(dplyr)
library(purrr)

DT <- DT %>% mutate(new = accumulate(A, FXN, .init = 0)[-1])

Will this work:

> DT$new <- cumsum(DT$A)
> DT
  A new
1 2   2
2 3   5
3 4   9
4 2  11
5 3  14
6 4  18
7 1  19
8 0  19

Checked it with sample data:

> start.time <- Sys.time()
> d <- data.frame(val = sample(1:100, 1000000, T))
> d$new <- cumsum(d$val)
> end.time <- Sys.time()
> time.taken <- end.time - start.time
> time.taken
Time difference of 0.1042359 secs
> 

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