在 R 中分割字符串并生成频率表
我在 R 数据框中有一列公司名称,内容如下:
"ABC Industries"
"ABC Enterprises"
"123 and 456 Corporation"
"XYZ Company"
等等。我正在尝试生成此列中出现的每个单词的频率表,例如,如下所示:
Industries 10
Corporation 31
Enterprise 40
ABC 30
XYZ 40
我对 R 相对较新,所以我想知道一种好方法来处理这。我应该拆分字符串并将每个不同的单词放入新列中吗?有没有一种方法可以将多字行拆分为多行,其中只有一个字?
I have a column of firm names in an R dataframe that goes something like this:
"ABC Industries"
"ABC Enterprises"
"123 and 456 Corporation"
"XYZ Company"
And so on. I'm trying to generate frequency tables of every word that appears in this column, so for example, something like this:
Industries 10
Corporation 31
Enterprise 40
ABC 30
XYZ 40
I'm relatively new to R, so I was wondering of a good way to approach this. Should I be splitting the strings and placing every distinct word into a new column? Is there a way to split up a multi-word row into multiple rows with one word?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你愿意,你可以用一句话来完成:
这里我使用
strsplit()
来打破每个条目介绍组件;这将返回一个列表(列表内)。我使用do.call()
,因此只需将所有结果列表连接到一个向量中,由table()
进行汇总。If you wanted to, you could do it in a one-liner:
Here I use
strsplit()
to break each entry intro components; this returns a list (within a list). I usedo.call()
so simply concatenate all result lists into one vector, whichtable()
summarises.这是另一句俏皮话。它使用
paste()
将所有列条目组合成一个长文本字符串,然后将其拆分并制成表格:Here is another one-liner. It uses
paste()
to combine all of the column entries into a single long text string, which it then splits apart and tabulates:您可以使用
tidytext
和dplyr
包:You can use the package
tidytext
anddplyr
: