计算数据帧 R 中字符串的频率

Count the frequency of strings in a dataframe R

我想计算数据框中某些字符串的频率。

strings  <- c("pi","pie","piece","pin","pinned","post")
df <- as.data.frame(strings)

然后我想计算字符串的频率:

counts <- c("pi", "in", "pie", "ie")

给我这样的东西:

string  freq
 pi       5
 in       2
 pie      2
 ie       2

我已经尝试过 grepltable,但我不知道如何指定要搜索的字符串。

您可以使用 sapply() 转到 counts 并使用 [=17= 将 counts 中的每个项目与 df 中的 strings 列匹配] 这将 return 一个 logical 向量(TRUE 如果匹配,FALSE 如果 non-match)。您可以将此向量相加以获得匹配数。

sapply(df, function(x) {
  sapply(counts, function(y) {
    sum(grepl(y, x))
  })
})

这将 return:

    strings
pi        5
in        2
pie       2
ie        2

频率 table 由 qgramsstringdist

创建
library(stringdist)
strings  <- c("pi","pie","piece","pin","pinned","post")
frequency <- data.frame(t(stringdist::qgrams(freq = strings, q = 2)))

   freq
pi    5
po    1
st    1
ie    2
in    2
nn    1
os    1
ne    1
ec    1
ed    1
ce    1
colSums(sapply(counts, stringr::str_count, string = df$strings))
 pi  in pie  ie 
  5   2   2   2 

您可以使用基数 R:

中的 adist
data.frame(counts,freq=rowSums(!adist(counts,strings,partial = T)))
  counts freq
1     pi    5
2     in    2
3    pie    2
4     ie    2

如果您熟悉正则表达式,那么您可以:

 a=sapply(paste0(".*(",counts,").*|.*"),sub,"\1",strings)
 table(grep("\w",a,value = T))
 ie  in  pi pie 
  2   2   5   2 

这是我的解决方案,仅使用基本 R 和 tidyverse 函数,但它可能不如人们提到的其他包有效。

new_df <- data.frame('VarName'=unique(df$VarName), 'Count'=0)

for (row_no in 1:nrow(new_df)) {
    new_df[row_no,'Count'] = df %>%
        filter(VarName==new_df[row_no, 'VarName']) %>%
        nrow()
}

您只需切换出 df 和 VarName。