你可以用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
编辑
# or set names directly within 'outer' as noted by @RichardScriven outer(setNames(nm = texts), setNames(nm = patterns), str_count)