R中for循环的矢量化

时间:2015-12-11 20:59:01

标签: r vectorization

我有两个载体:

  • 文本矢量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

2 个答案:

答案 0 :(得分:8)

您可以使用<?php $colors =array("red","green","orange","blue"); $colorLen = count($colors); ?> <!DOCTYPE html> <html> <head> <link href="stylesheets/reset.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/normalize.css" rel="stylesheet" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <title></title> <style type="text/css"> .myDiv{float:left; width:150px; height:150px; margin:10px;} .myDiv img{width:100%; height: 100%;} .myDiv p{text-align: center; margin: 0px; padding: 0px;} .hidden{display: none;} .myLink{margin:20px;} #prev{float: left;} #next{float: right;} </style> <script type="text/javascript"> $(document).ready(function() { $("#0").removeClass("hidden"); //set the first div to be visible }); </script> </head> <body style="display:inline-block; width:auto;"> <a id="prev" class="myLink" href="#">Prev</a> <?php //Cycle through the colors and create a div with image and title tag $i =0; while ($i != $colorLen) { echo '<div id="'.$i.'" class="myDiv hidden" style="background-color:'.$colors[$i].';"> <img src="#" alt="'.$colors[$i].'"/><p>'.ucfirst($colors[$i]).'</p> </div>'; $i++; } ?> <a id="next" class="myLink" href="#">Next</a> <script type="text/javascript"> var numItems =$('.myDiv').length; //Get the number of elements on the page </script> </body> </html> 。我假设您使用outer包中的str_count

stringr

修改

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

答案 1 :(得分:3)

使用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