Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9054881
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T13:47:52+00:00 2026-06-16T13:47:52+00:00

Following those conversations: Can I vectorize a calculation which depends on previous elements sapply?

  • 0

Following those conversations:

  1. Can I vectorize a calculation which depends on previous elements
  2. sapply? tapply? ddply? dataframe variable based on rolling index of previous values of another variable

I wanted to test a more “real-life” case-study.
I recently had to migrate SAS code to R and kdb code to R code. I tried to compiled a simple enough yet more sophisticated example to optimize.

let’s build the training set

buildDF <- function(N){
    set.seed(123); dateTimes <- sort(as.POSIXct("2001-01-01 08:30:00") + floor(3600*runif(N)));
    set.seed(124); f <- floor(1+3*runif(N));
    set.seed(123); s <- floor(1+3*runif(N));
    return(data.frame(dateTime=dateTimes, f=f, s=s));
}

This is what need to be achieved

f1 <- function(DF){
    #init
    N <- nrow(DF);
    DF$num[1] = 1;

    for(i in 2:N){
        if(DF$f[i] == 2){
            DF$num[i] <- ifelse(DF$s[i-1] == DF$s[i],DF$num[i-1],1+DF$num[i-1]);        
        }else{ #meaning f in {1,3}
            if(DF$f[i-1] != 2){
                DF$num[i] = DF$num[i-1]; 
            }else{
                DF$num[i] = ifelse((DF$dateTime[i]-DF$dateTime[i-1])==0,DF$num[i-1],1+DF$num[i-1]);
            }
        }
    }
    return(DF)
}

This is off course hideous. Let’s vectorize it a bit:

f2 <- function(DF){
    N <- nrow(DF);
    DF$add <- 1; DF$ds <- c(NA,diff(DF$s)); DF$lf <- c(NA,DF$f[1:(N-1)]);
    DF$dt <- c(NA,diff(DF$dateTime));
    DF$add[DF$f == 2 & DF$ds == 0] <- 0;
    DF$add[DF$f == 2 & DF$ds != 0] <- 1;
    DF$add[DF$f != 2 & DF$lf != 2] <- 0;
    DF$add[DF$f != 2 & DF$lf == 2 & DF$dt==0] <- 0;
    DF$num <- cumsum(DF$add);
    return(DF);
}

And using the most useful data.table:

f3 <- function(DT){
    N <- nrow(DT);
    DT[,add:=1]; DT[,ds:=c(NA,diff(s))]; DT[,lf:=c(NA,f[1:(N-1)])];
    DT[,dt:=c(NA,diff(dateTime))];
    DT[f == 2 & ds == 0, add:=0];
    DT[f == 2 & ds != 0, add:=1];
    DT[f != 2 & lf != 2, add:=0];
    DT[f != 2 & lf == 2 & dt == 0, add:=0];
    DT[,num:=cumsum(add)];
    return(DT);
}

On a 10K data-frame:

library(rbenchmark);
library(data.table);

N <- 1e4;
DF <- buildDF(N)
DT <- as.data.table(DF);#we can contruct the data.table as a data.frame so it's ok we don't count for this time.

#make sure everybody is equal
DF1 <- f1(DF) ; DF2 <- f2(DF); DT3 <- f3(DT);
identical(DF1$num,DF2$num,DT3$num) 
[1] TRUE

#let's benchmark
benchmark(f1(DF),f2(DF),f3(DT),columns=c("test", "replications", "elapsed",
+ "relative", "user.self", "sys.self"), order="relative",replications=1);
    test replications elapsed relative user.self sys.self
2 f2(DF)            1   0.010      1.0     0.012    0.000
3 f3(DT)            1   0.012      1.2     0.012    0.000
1 f1(DF)            1   9.085    908.5     8.980    0.072

Ok, now on a more decent 5M rows data.frame

N <- 5e6;
DF <- buildDF(N)
DT <- as.data.table(DF);
benchmark(f2(DF),f3(DT),columns=c("test", "replications", "elapsed",       
+ "relative", "user.self", "sys.self"), order="relative",replications=1);
    test replications elapsed relative user.self sys.self
2 f3(DT)            1   2.843    1.000     2.092    0.624
1 f2(DF)            1  10.920    3.841     4.016    5.137

We gain 5X with data.table.

I wonder if Rcpp or zoo:::rollapply can gain much on this.
I would be happy with any suggestion

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T13:47:53+00:00Added an answer on June 16, 2026 at 1:47 pm

    Simple inline Rcpp version:

    library(Rcpp)
    library(inline)
    
    f4cxx <- cxxfunction(signature(input="data.frame"), plugin="Rcpp", body='
      Rcpp::DataFrame df(input);
      const int N = df.nrows();  
    
      Rcpp::NumericVector f = df["f"];
      Rcpp::NumericVector s = df["s"];
      Rcpp::NumericVector d = df["dateTime"]; // As far as we need only comparation
      Rcpp::NumericVector num(N);             // it is safe to convert Datetime to Numeric (faster) 
    
      num[0] = 1;
      for(int i=1; i<N; i++){
        bool cond1 = (f[i]==2) && (s[i]!=s[i-1]);
        bool cond2 = (f[i]!=2) && (f[i-1]==2) && (d[i]!=d[i-1]);
        num[i] = (cond1 || cond2)?1+num[i-1]:num[i-1];    
      }
    
      df["num"] = num;
      return df;                                // Returns list
      //return (Rcpp::as<Rcpp::DataFrame>(df)); // Returns data.frame (slower)
      ')
    

    Checking out:

    N<-1e4; df<-buildDF(N)
    identical(f1(df)$num, f4cxx(df)$num)
    
    [1] TRUE
    

    Benchmarking:

    N<-1e5; df<-buildDF(N); dt<-as.data.table(df)
    benchmark(f2(df), f2j(df), f3(dt), f4cxx(df),
              columns=c("test", "replications", "elapsed", "relative", "user.self", "sys.self"),
              order="relative", replications=1);
    
           test replications elapsed relative user.self sys.self
    4 f4cxx(df)            1   0.001        1     0.000        0
    2   f2j(df)            1   0.037       37     0.040        0
    3    f3(dt)            1   0.058       58     0.056        0
    1    f2(df)            1   0.078       78     0.076        0
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

please help me to identify which of these following is more optimized code? for(int
I wrote the following script for a page which has been loaded with a
I am validating the following page : -removed and I got 13 errors Those
This is one of those you can do it many ways questions. Consider the
If I manually write those following lines in an HTML file: <div> <input type=button
I want to display contacts in my application with following criteria: contacts those match
http://www.boost.org/boost-build2/doc/html/bbv2/installation.html Tried following those instructions, but they do not work. What I did: Open
After following these steps: http://developers.facebook.com/docs/mobile/android/build/ I find that everything goes well, but when I
By following these instruction about autocompletion. I create an Index named suggestions. But when
I'm trying to get my local dev django app to work after following these

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.