Patrick
Patrick

Reputation: 32374

Apply function with two factored vectors of different length

I have a function which takes two vectors that are of differing lengths. The function is fed monthly data from a vector of daily data spanning multiple years. So far I have been "manually" split()ting the data and running a loop over the months, more or less like so:

f1 <- as.factor(substring(names(data1), 1, 7))
s1 <- split(data1, f1)
f2 <- as.factor(substring(names(data2), 5, 9)) # the objects specify dates differently 
s2 <- split(data2, f2)

res <- vector("list", 12)
for (i in 1:12) {
  res[[i]] <- my_func(s1[[i]], s2[[i]])
}

Is there a more elegant way to do this? The apply() family of functions don't seem to do the trick - lapply() takes only one list, for example, and nesting lists in a master list doesn't work either; mapply() takes multiple arguments but goes through the elements one by one while I need to process multiple elements at a time.

Upvotes: 1

Views: 58

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35649

You could use Map(equivalent to mapply(..., SIMPLIFY = FALSE)) to apply a function over multiple list or vector arguments.

res <- Map(my_func, s1, s2)

Upvotes: 1

Related Questions