将函数应用于两个不同长度的向量,return R 中的一个矩阵
Apply function over two vectors of different lengths, and return a matrix in R
我有两个不同长度的向量,我想对这两个向量的所有可能组合应用一个函数,从而得到一个矩阵。
在我的特定示例中,这两个向量是字符向量,我想应用函数 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
等做了很多研究,但没有找到我要找的东西。
感谢您的帮助。
试试这个
library(stringr)
t(sapply(names,str_detect,pattern=slices))
您也可以使用 grepl
在 base R 中执行此操作
sapply(slices, grepl, names)
我有两个不同长度的向量,我想对这两个向量的所有可能组合应用一个函数,从而得到一个矩阵。
在我的特定示例中,这两个向量是字符向量,我想应用函数 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
等做了很多研究,但没有找到我要找的东西。
感谢您的帮助。
试试这个
library(stringr)
t(sapply(names,str_detect,pattern=slices))
您也可以使用 grepl
sapply(slices, grepl, names)