[英]Apply function over two vectors of different lengths, and return a matrix in R
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: 在我的特定示例中,两个向量是charactor向量,我想应用函数
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
but I am sure there is a better and more efficient way. 现在我正在使用
for loops
但我相信有更好,更有效的方法。 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. 我已经对
apply functions
进行了大量的研究,以及aggregate
, by
, sweep
等,但还没有找到我想要的东西。
Thanks for the help. 谢谢您的帮助。
Try this 试试这个
library(stringr)
t(sapply(names,str_detect,pattern=slices))
You can also do this in base R using grepl
您也可以使用
grepl
在base R中执行此grepl
sapply(slices, grepl, names)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.