Skip to content

EvenOdd Function Optimization #38

@vittorio-g

Description

@vittorio-g

As previously discussed with @ryentes, I'm posting the code to optimize the "evenodd" function. This code should compute the values more or less ten times faster than the old function. Hope this helps!

evenodd2 <- function(x,factors){
  
  #objects needed
  odd_means <- data.frame(matrix(nrow = nrow(x),
                      ncol = length(factors)))
  even_means <- data.frame(matrix(nrow = nrow(x),
                       ncol = length(factors)))
  j <- 1
  a <- 0
  for(i in factors){
    #Creating a sequence of odd and even numbers
    even <- seq(2,max(factors),2)
    odd <- seq(1,max(factors),2)
    
    #factor selection
    a <- a+i
    sec <- x[,(a-i+1):a]
    
    #odd and even numbers of items selection
    o <- odd[1:round(i/2)]
    e <- even[1:(round(i/2)-1)]
    
    #row means of sections
    odd_means[,j] <- apply(sec[o],1,mean,na.rm=T)
    even_means[,j] <- apply(sec[e],1,mean,na.rm=T)
    
    j <- j+1  
  }
  
  #Correlation
  corr <- sapply(1:nrow(odd_means), function(i){
    cor(
      as.numeric(odd_means[i,]),
      as.numeric(even_means[i,]),
      use="complete.obs"
    )
  }
  )
  
  #Spearman-Brown and inversion 
  eoi <- -2*corr/(1 + corr)
  eoi
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions