RobinHankin / permutations

https://robinhankin.github.io/permutations/
5 stars 3 forks source link

as.function() not vectorised #54

Closed RobinHankin closed 1 month ago

RobinHankin commented 1 month ago
library("permutations")
#> 
#> Attaching package: 'permutations'
#> The following object is masked from 'package:stats':
#> 
#>     cycle
(o <- allperms(3))
#> [1] ()    (23)  (12)  (123) (132) (13) 
#> [coerced from word form]
x <- c(1,2,3,3,2,1)
as.function(o)(1)
#> [1] 1 1 2 2 3 3
as.function(o[2])(x)
#> [1] 1 3 2 2 3 1
as.function(o)(x)
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    1    2    3    3    2    1
#> [2,]    1    3    2    2    3    1
#> [3,]    2    1    3    3    1    2
#> [4,]    2    3    1    1    3    2
#> [5,]    3    1    2    2    1    3
#> [6,]    3    2    1    1    2    3

Created on 2024-08-29 with reprex v2.1.1

Above, the first two use-cases of as.function(o) work fine but the third does not behave as expected. For the record, I would expect

library("permutations")
#> 
#> Attaching package: 'permutations'
#> The following object is masked from 'package:stats':
#> 
#>     cycle
(o <- allperms(3))
#> [1] ()    (23)  (12)  (123) (132) (13) 
#> [coerced from word form]
x <- c(1,2,3,3,2,1)
sapply(1:6,function(i){as.function(o[i])(x[i])})
#> [1] 1 3 3 1 1 3
RobinHankin commented 1 month ago

or, better,

library("permutations")
(o <- allperms(3))
#> [1] ()    (23)  (12)  (123) (132) (13) 
#> [coerced from word form]
x <- c(1,2,3,3,2,1)
as.matrix(o)[cbind(seq_len(6),x)]
#> [1] 1 3 3 1 1 3