Error taking the difference within a function

Viewed 16

the function below is one that I have previously been able to use when fulldiam has been a vector.

dN <- sapply(df,function(dn,fulldiam) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam))),fulldiam)

In this function, df is a numeric data.frame (dim = 99 x 1399) and fulldiam is a numeric vector (length = 99).

I am trying to alter the data by altering the fulldiam vector to where it is slightly different for each. So now I am trying to use fulldiam_shifted which is a numeric data.frame (dim = 99 x 1399). When I try to run the function with the change I get an error.

dN_shift <- sapply(df,function(dn,fulldiam_shifted) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam_shifted))),fulldiam_shifted)

Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] : 
  non-numeric argument to binary operator

I believe the issue is that the fulldiam_shifted needs to have each column called for each row of df. Is there any recommendations on what could be done to allow this function to work?

1 Answers

We may use Map here as both the datasets are of equal dimensions

Map(function(dn, fulldiam_new) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam_new))), df, fulldiam_shifted)
Related