【问题标题】:Apply function over two vectors of different lengths, and return a matrix in R在两个不同长度的向量上应用函数,并在 R 中返回一个矩阵
【发布时间】: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,以及aggregatebysweep等做了很多研究,但还没有找到我想要的。

感谢您的帮助。

【问题讨论】:

  • 检查outer函数。
  • outer(names, slices, stringr::str_detect)
  • 你也可以用`dimnames&lt;-`(outer(names, slices, stringr::str_detect), list(names, slices))设置名字,觉得两行可能更漂亮。

标签: r string matrix vector apply


【解决方案1】:

试试这个

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

您也可以在基础 R 中使用 grepl 执行此操作

sapply(slices, grepl, names)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 2017-12-13
    • 2022-06-17
    • 2020-06-18
    • 2016-07-04
    • 1970-01-01
    相关资源
    最近更新 更多