Maharero
Maharero

Reputation: 248

For-loop and Lapply: Same function gives different results

I want to iterate a function over a list of vectors. I'm trying to use Lapply however this is giving unwanted results whilst a for loop with the same arguments has the correct results:

Reproducible example:

library(gtools) # for 'permutations' function
exampleList <- list(c("RETURN", "COMBINATIONS"), c(1,2,3), c("PLEASE WORK") )

Desired output (what the for-loop returns):

for (i in 1:length(exampleList)) {
  print( permutations(n = length(exampleList[[i]]), r = length(exampleList[[i]]), v = exampleList[[i]]))
}

     [,1]           [,2]          
[1,] "COMBINATIONS" "RETURN"      
[2,] "RETURN"       "COMBINATIONS"
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1
     [,1]         
[1,] "PLEASE WORK"

What the Lapply version currently returns:

lapply(exampleList, permutations, n = length(exampleList), r = length(exampleList))

Error in FUN(X[[i]], ...) : v is either non-atomic or too short

If I understand correctly, lapply iterates through each exampleList[[i]] so the 'v' argument doesnt need to be specified (note I still get an error when trying to specify it). What is causing my results to be inconsistent?

Upvotes: 1

Views: 269

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

In your attempt you are giving values of n and r to be length(exampleList). However, it should be equal to length of each individual element in the list.

lapply(exampleList, function(x) 
        gtools::permutations(n = length(x), r = length(x), v = x))


#[[1]]
#     [,1]           [,2]          
#[1,] "COMBINATIONS" "RETURN"      
#[2,] "RETURN"       "COMBINATIONS"

#[[2]]
#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    1    3    2
#[3,]    2    1    3
#[4,]    2    3    1
#[5,]    3    1    2
#[6,]    3    2    1

#[[3]]
#     [,1]         
#[1,] "PLEASE WORK"

You can also write this with Map

Map(function(x, y) gtools::permutations(n = y, r = y, v = x), 
                   exampleList, lengths(exampleList))

Upvotes: 1

Related Questions