【发布时间】:2016-12-20 11:34:12
【问题描述】:
我有两个不同长度的向量,我想对这两个向量的每个可能组合应用一个函数,从而得到一个矩阵。
在我的具体例子中,这两个向量是字符向量,我想应用函数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
现在我正在使用for loops,但我确信有更好、更有效的方法。我对apply functions,以及aggregate、by、sweep等做了很多研究,但还没有找到我想要的。
感谢您的帮助。
【问题讨论】:
-
检查
outer函数。 -
outer(names, slices, stringr::str_detect) -
你也可以用
`dimnames<-`(outer(names, slices, stringr::str_detect), list(names, slices))设置名字,觉得两行可能更漂亮。
标签: r string matrix vector apply