Home > database >  Function works normally. But when used with sapply in order to pass each value of a vector as one of
Function works normally. But when used with sapply in order to pass each value of a vector as one of

Time:02-19

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.

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.

CodePudding user response:

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))
  • Related