Amadou Kone - 1 year ago 61

R Question

I have two vectors of different lengths, and I would like to apply a function to every possible combination of the two vectors, resulting in a matrix.

In my particular example, the two vectors are charactor vectors, and I would like to apply the function

`grepl`

`names <- c('cats', 'dogs', 'frogs', 'bats')`

slices <- c('ca', 'at', 'ts', 'do', 'og', 'gs', 'fr', 'ro', 'ba')

results <- someFunction(grepl, names, slices)

results

ca at ts do og gs fr ro ba

cats TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE

dogs FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE

frogs FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE

bats FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE

Right now I am using

`for loops`

`apply functions`

`aggregate`

`by`

`sweep`

Thanks for the help.

Answer Source

Try this

```
library(stringr)
t(sapply(names,str_detect,pattern=slices))
```

You can also do this in base R using `grepl`

```
sapply(slices, grepl, names)
```