jeudi 24 août 2017

ifelse clause inside Map() or lapply() in order to change the behavior of combn()

After executing some code I'm getting this list

> test
$M
     start end
[1,]     1   1
[2,]     2   2

$M
     start end
[1,]     1   1
[2,]     2   2

$C
     start end
[1,]     5   5

which represents the occurrences of characters (M , C) in a string. That list then I pass it through the following Map() call in order to get all possible combinations for each of these characters.

ind1 = Map( function(x) lapply(1:nrow(test[[x]]), combn , x=test[[x]][,1]) , 1:length(test) )

The result of that code looks like :

> ind1
[[1]]
[[1]][[1]]
     [,1] [,2]
[1,]    1    2

[[1]][[2]]
     [,1]
[1,]    1
[2,]    2


[[2]]
[[2]][[1]]
     [,1] [,2]
[1,]    1    2

[[2]][[2]]
     [,1]
[1,]    1
[2,]    2


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

In other words it is doing the following

# For 1st item
combn(test[[1]][,] , 1 )
combn(test[[1]][,] , 2 )

# For 2nd item
combn(test[[2]][,] , 1 )
combn(test[[2]][,] , 2 )

# For 3rd item
combn(test[[3]][,] , 1 )

So the problem is in the 3rd item. As you can see there is only one occurrence of the character "C" in the string and it's the fifth character.

The expected in that case for possible combinations results for the third item would be something like this

[[3]]
[[3]][[1]]
     [,1] 
[1,]    5

and not

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

That happens because combn() in my code is becoming combn(5, 1 ). So I was wondering if there is any way to add an ifelse clause in my Map() or lapply() to check if there is only one occurrence and if it's TRUE to let it as it has and not execute the combn() part.

Thank you.

Aucun commentaire:

Enregistrer un commentaire