本文介绍了在两个不同长度的向量上应用函数,并在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.

在我的特定示例中,两个向量是字符向量,我想应用函数grepl,即:

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

现在我正在使用for loops,但是我确信有一种更好,更有效的方法.我已经对apply functions以及aggregatebysweep等进行了大量研究,但没有找到我想要的东西.

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.

感谢您的帮助.

推荐答案

尝试一下

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

您也可以使用grepl

sapply(slices, grepl, names)

这篇关于在两个不同长度的向量上应用函数,并在R中返回一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 17:54