【问题标题】:Vectorization of a for-loop in RR中for循环的向量化
【发布时间】:2015-12-11 20:59:01
【问题描述】:

我有两个向量:

  • 文本向量c('abc', 'asdf', 'werd', 'ffssd')
  • 模式向量c('ab', 'd', 'w')

我想矢量化以下 for 循环:

for(p in 1 : length(patterns)){
    count <- count + str_count(texts, p);
}

我使用了以下命令,但都不起作用。

> str_count(texts, patterns)
[1] 1 1 1 0
Warning message:
In stri_count_regex(string, pattern, opts_regex = attr(pattern,  :
  longer object length is not a multiple of shorter object length

> str_count(texts, t(patterns))
[1] 1 1 1 0
Warning message:
In stri_count_regex(string, pattern, opts_regex = attr(pattern,  :
  longer object length is not a multiple of shorter object length

我想要一个像这样的二维矩阵:

       |  patterns
 ------+--------
       |   1 0 0
 texts |   0 1 0
       |   0 1 1
       |   0 1 0

【问题讨论】:

  • matrix(stringr::str_count(rep(texts, length(patterns)), rep(patterns, each = length(texts))), length(texts), dimnames = list(texts, patterns))

标签: r vectorization


【解决方案1】:

您可以使用outer。我假设您使用的是 stringr 包中的 str_count

library(stringr)

texts <- c('abc', 'asdf', 'werd', 'ffssd')
patterns <- c('ab', 'd', 'w')

matches <- outer(texts, patterns, str_count)

# set dim names
colnames(matches) <- patterns
rownames(matches) <- texts
matches
      ab d w
abc    1 0 0
asdf   0 1 0
werd   0 1 1
ffssd  0 1 0

编辑

# or set names directly within 'outer' as noted by @RichardScriven
outer(setNames(nm = texts), setNames(nm = patterns), str_count)

【讨论】:

  • 不错的一个。您也可以在outer() 调用中设置名称。 outer(setNames(nm = texts), setNames(nm = patterns), str_count)
【解决方案2】:

使用dplyrtidyr(和stringr):

library(dplyr)
library(tidyr)
library(stringr)
expand.grid(texts, patterns) %>%
   mutate_each(funs(as.character(.))) %>%
   mutate(matches = stringr::str_count(Var1, Var2)) %>% 
   spread(Var2, matches)
   Var1 ab d w
1   abc  1 0 0
2  asdf  0 1 0
3 ffssd  0 1 0
4  werd  0 1 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    相关资源
    最近更新 更多