Apply the function to two vectors of different lengths and return the matrix to R

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

In my specific example, two vectors are characteristic vectors, and I would like to apply a function grepl, that is:

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

I am using now for loops, but I am sure that there is a better and more efficient way. I spent a lot of research on apply functions, and aggregate, by, sweepand so on, but have not found what I'm looking for.

Thanks for the help.

+4
source share
1 answer

try it

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

R, grepl

sapply(slices, grepl, names)
+3

Source: https://habr.com/ru/post/1651168/


All Articles