我在R数据框中有一列公司名称,如下所示:
"ABC Industries"
"ABC Enterprises"
"123 and 456 Corporation"
"XYZ Company"
以此类推。我试图生成本列中出现的每个单词的频率表,例如,如下所示:
Industries 10
Corporation 31
Enterprise 40
ABC 30
XYZ 40
我对R比较陌生,所以我想知道一个好方法来解决这个问题。我是否应该拆分字符串并将每个不同的单词放入一个新列中?是否有一种方法可以将一个多词行拆分为多个行与一个词?
如果您愿意,您可以在一行代码中完成:
R> text <- c("ABC Industries", "ABC Enterprises",
+ "123 and 456 Corporation", "XYZ Company")
R> table(do.call(c, lapply(text, function(x) unlist(strsplit(x, " ")))))
123 456 ABC and Company
1 1 2 1 1
Corporation Enterprises Industries XYZ
1 1 1 1
R>
这里我使用strsplit()
来打破每个条目介绍组件;这将返回一个列表(在列表中)。我使用do.call()
,所以简单地将所有结果列表连接到一个向量,table()
总结。
下面是另一个一行代码。它使用paste()
将所有列条目组合成一个长文本字符串,然后将其分开并制表:
text <- c("ABC Industries", "ABC Enterprises",
"123 and 456 Corporation", "XYZ Company")
table(strsplit(paste(text, collapse=" "), " "))
您可以使用tidytext
和dplyr
包:
set.seed(42)
text <- c("ABC Industries", "ABC Enterprises",
"123 and 456 Corporation", "XYZ Company")
data <- data.frame(category = sample(text, 100, replace = TRUE),
stringsAsFactors = FALSE)
library(tidytext)
library(dplyr)
data %>%
unnest_tokens(word, category) %>%
group_by(word) %>%
count()
#> # A tibble: 9 x 2
#> # Groups: word [9]
#> word n
#> <chr> <int>
#> 1 123 29
#> 2 456 29
#> 3 abc 45
#> 4 and 29
#> 5 company 26
#> 6 corporation 29
#> 7 enterprises 21
#> 8 industries 24
#> 9 xyz 26