Apply function over two vectors of different lengths, and return a matrix in R

会有一股神秘感。 提交于 2019-12-07 02:51:51

问题


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, ie:

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 but I am sure there is a better and more efficient way. I have done a lot of research on the apply functions, as well as aggregate, by, sweep, etc, but haven't found what I am looking for.

Thanks for the help.


回答1:


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)


来源:https://stackoverflow.com/questions/38935146/apply-function-over-two-vectors-of-different-lengths-and-return-a-matrix-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!