当每个句子在数据框中单独一行时计算整体词频

Counting overall word frequency when each sentence is a separate row in a dataframe

我有一个包含人名的数据框列。有些名字只有一个词,即名字)。有些名字有两个词,即名字和姓氏,用 space 分隔。有些名字有三个词,名字、中间名和姓氏由 space 分隔。例如

Luke
Luke Skywalker
Walk Sky Luker
Walk Luke Syker 

一些名字有四个或更多的单词。我想找到每个单词的频率,例如

Luke 3
Walk 2
Sky 1
Skywalker 1
Luker 1
Skyer 1

我如何使用 R 实现它?我试过使用 stringr 提取单词。当单词以单个文本块(如段落)的形式出现时,我能够将它们分开。但是当行中的每个名称都在单独的数据框中时,我无法分隔单词。有帮助吗?

#Convert the data.frame column to a vector
a=as.vector(your.df$column.name)

#convert the vector elements into one string
b=paste(a, collapse=' ')

#Split the string by space to get individual words, then get frequencies
table(strsplit(b,' ')[[1]])

您可以只在您的专栏

的未列出 strsplit() 上使用 table()
table(unlist(strsplit(df$Words, " ")))

# Luke     Luker       Sky Skywalker     Syker      Walk 
#    3         1         1         1         1         2 

如果你需要它排序

sort(table(unlist(strsplit(df$Words, " "))), decreasing = TRUE)

#     Luke      Walk     Luker       Sky Skywalker     Syker 
#        3         2         1         1         1         1 

其中 df$words 是您感兴趣的栏目。

df %>%
  tidyr::separate_rows(V1, sep = '\s+') %>%
  dplyr::count(V1, sort = TRUE)

#  V1            n
#  <chr>     <int>
#1 Luke          3
#2 Walk          2
#3 Luker         1
#4 Sky           1
#5 Skywalker     1
#6 Syker         1

数据

df <- structure(list(V1 = c("Luke", "Luke Skywalker", "Walk Sky Luker", 
"Walk Luke Syker")), class = "data.frame", row.names = c(NA, -4L))