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

Function works normally. But when used with sapply in order to pass each value of a vector as one of the arguments, I get an error

Sorry for the bad phrasing of the question!

I created a function, abc, and it works fine with my data table, DT, by itself.

#function
abc <- function(DT, ucol="u", vcol="v", xdiff = 3) {
  #find n
  result1 = DT[DT[,x2:= x_coord. + xdiff ], on=.(y_coord, x_coord=x2), nomatch=0]
  result1[, ucol_values:=get(ucol)]
  n_points <- nrow(result1)                   #N
  
  #find (ui-uj)*(vi-vj)
  result2 = result1
  result[, prod:=(get(ucol)-get(paste0("i.",ucol)))*(get(vcol)-get(paste0("i.",vcol)))][, .(row_a=row, row_b=i.row, prod)]
  sum_prod_result<- sum(result2$prod)
    
  resultlist<- list("xdiff"=xdiff, "sum of products"=sum_prod_result, "n"=n_points)
  
  return(resultlist)
}

>abc(DT)
$`xdiff`
[1] 5

$`sum of products`
[1] -0.731064

$n
[1] 43

I have a vector x and I want to repeat the function with xdiff equal to each value of x.

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

x <- (5,10,15,20,25)

sapply<- (xdiffs, abc, xdiff=x)

But I get the following error with sapply:

Error in :=(x2, x_coord. + xdiff) :
Check that is.data.table(DT) == TRUE. Otherwise, := and :=(…) are defined for use in j, once only and in particular ways. See help(":=").

I checked the class of DT and it is a data table. I’m not sure how to fix this issue.

>Solution :

sapply iterates only over the first argument provided, so you would need to change the function call to something like:

sapply(x, function(i) abc(DT, xdiff = i))
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