Data.table function for row is too slow

I need to calculate the weighted funds per line (6M + lines), but it takes a lot of time. The column with weights is a character field, so weighted.mean cannot be used directly.

Background data:

library(data.table)
library(stringr)
values <- c(1,2,3,4)
grp <- c("a", "a", "b", "b")
weights <- c("{10,0,0,0}", "{0,10,0,0}", "{10,10,0,0}", "{0,0,10,0}")
DF <- data.frame(cbind(grp, weights))
DT <- data.table(DF)

string.weighted.mean <- function(weights.x) {
  tmp.1 <- na.omit(as.numeric(unlist(str_split(string=weights.x, pattern="[^0-9]+"))))
  tmp.2 <- weighted.mean(x=values, w=tmp.1)
}

Here's how to do it (too slowly) with data.frames:

DF$wm <- mapply(string.weighted.mean, DF$weights)

This runs, but too slowly (hours):

DT[, wm:=mapply(string.weighted.mean, weights)]

How can I rephrase the last line to speed things up?

+5
source share
2 answers
DT[, rowid := 1:nrow(DT)]
setkey(DT, rowid)
DT[, wm :={
    weighted.mean(x=values, w=na.omit(as.numeric(unlist(str_split(string=weights, pattern="[^0-9]+")))))     
}, by=rowid]
+6
source

Since the group does not seem to have anything to do with calculating the weighted value, I tried to simplify the problem a bit.

     values <- seq(4)

# A function to compute a string of length 4 with random weights 0 or 10
     tstwts <- function()
     {
         w <- sample( c(0, 10), 4, replace = TRUE )
         paste0( "{", paste(w, collapse = ","), "}" )
     }

# Generate 100K strings and put them into a vector
     u <- replicate( 1e5, tstwts() )
     head(u)   # Check
     table(u)

# Function to compute a weighted mean from a string using values 
# as an assumed external numeric vector 'values' of the same length as
# the weights
    f <- function(x)
         {
             valstr <- gsub( "[\\{\\}]", "", x )
             wts <- as.numeric( unlist( strsplit(valstr, ",") ) )
             sum(wts * values) / sum(wts) 
         }

# Execute the function f recursively on the vector of weights u
    v <- sapply(u, f)

# Some checks:
    head(v)
    table(v)

On my system, for 100K repetitions,

> system.time(sapply(u, f))
   user  system elapsed 
   3.79    0.00    3.83

The data table version of this group (sans) will be

DT <- data.table( weights = u )
DT[, wt.mean := lapply(weights, f)] )
head(DT)
dim(DT)

On my system, it takes

system.time(DT [, wt.mean: = lapply (weight, f)])                3,62 0,03 3,69

35-40 , (Win7, 2,8 , 8 ). YMMV.

+2

All Articles