Search code examples
rlistpurrr

Change first input based on second input, applying a function, using purrr´s map2


I'm wondering if it's possible to change, let's say .x based on .y applying map2() on the fly, applying a function.

Let's say I have two vectors with different lengths and want to fill shortest one with NA, in order to have same length in both vectors:

vec1 <- seq(1, 3, by = 2)
vec2 <- seq(2, 3, by = 2)

Both solutions are valid:

  1. length(vec2) <- length(vec1)

  2. `<-`(length(vec2), length(vec1))

But, what if I have vectors in lists, and want to apply purrr's map2?

l1 <- list(c(1,2), c(1,2))
l2 <- list(3, 3)

I have tried:

library(purrr)

map2(l1, l2, ~ `<-`(length(.y), length(.x)))

but does not work. Any ideas how to assign a value inside map2?

PS: I'm trying to avoid using loops.


Solution

  • You should call `length<-` rather than `<-`.

    purrr::map2(l1, l2, ~ `length<-`(.y, length(.x)))
    
    # [[1]]
    # [1]  3 NA
    # 
    # [[2]]
    # [1]  3 NA
    

    which is equivalent to

    purrr::map2(l1, l2, ~ { length(.y) <- length(.x); .y })