Vit
Vit

Reputation: 77

apply function to each column using different parameters

I want to apply the BoxCox function to each column of a time series matrix:

lapply(ts_data, function(x,lambda) {BoxCox(x,lambda)}, lambda = 0.4)

The problem is, that I don't want to fix lambda for each column to a fixed global parameter. Instead I have a vector vec_lambda containing different lambdas, for each column of ts_data some different vec_lambda was precalculated.

Any idea how to use lapply or something similar?

Upvotes: 0

Views: 276

Answers (2)

Justin Landis
Justin Landis

Reputation: 2071

Additionally, you could use mapply, mapply has methods for data.frame and list

#a bit modified from mapply help page example
mapply(function(x, y) sqrt(x) + y,  #BoxCox
   data.frame(x=c(1,2,3),y=c(4,5,6),z=c(7,8,9)),  #ts_data
   c(A = 10, B = 0, C = -10)) .  #lambda

Upvotes: 0

akrun
akrun

Reputation: 886948

If it is a data.frame, we can use Map

Map(BoxCox, ts_data, lambda = v1)

where 'v1' is the vector of lambda values which is equal to the number of columns of the 'ts_data'


If it is a matrix, then loop through the sequence of columns

lapply(seq_len(ncol(ts_data)), function(i) BoxCox(ts_data[,i], lambda = v1[i]))

Upvotes: 1

Related Questions