在R语言中拆分自由文本字段时保留分组关联的方法
拆分研究方向文本并按年级分层统计
你可以用tidyverse里的separate_rows函数拆分文本,同时保留Year变量的关联,轻松实现分层统计和后续绘图。以下是完整解决代码和说明:
完整代码
library(tidyverse) library(tidytext) # 1. 拆分文本并保留年级信息 data_research_processed <- data_research %>% separate_rows(Please.list.your.research.interests, sep = ", ") %>% rename(research_topic = Please.list.your.research.interests) # 重命名列方便后续操作 # 2. 统计每个研究方向的总出现次数 total_count <- data_research_processed %>% count(research_topic, sort = TRUE) %>% rename(total = n) # 3. 统计每个研究方向在各年级的出现次数 yearly_count <- data_research_processed %>% count(Year, research_topic, sort = TRUE) %>% rename(yearly_n = n) # 可选:合并总数量和年级数量,方便同时查看 combined_count <- total_count %>% left_join(yearly_count, by = "research_topic")
关键步骤说明
separate_rows函数:核心工具,能把逗号分隔的文本拆成独立行,同时完整保留原数据的所有变量(包括Year),避免了原代码用strsplit丢失分组信息的问题。- 总数量统计:直接对拆分后的
research_topic列计数,得到每个研究方向的总出现次数。 - 年级分层统计:通过
count(Year, research_topic)按年级和研究方向分组计数,得到各年级对应的数量,正好满足后续分层绘图的需求。
示例测试结果
用你提供的示例数据:
data_research <- tibble( Please.list.your.research.interests = c("Vaccines, TB, HIV", "TB, Chronic Diseases"), Year = c("1st year", "2nd year") )
运行代码后,total_count的结果为:
| research_topic | total |
|---|---|
| TB | 2 |
| Vaccines | 1 |
| HIV | 1 |
| Chronic Diseases | 1 |
yearly_count的结果为:
| Year | research_topic | yearly_n |
|---|---|---|
| 1st year | TB | 1 |
| 1st year | Vaccines | 1 |
| 1st year | HIV | 1 |
| 2nd year | TB | 1 |
| 2nd year | Chronic Diseases | 1 |
分层绘图示例
基于yearly_count可以直接绘制分层条形图:
ggplot(yearly_count, aes(x = reorder(research_topic, yearly_n), y = yearly_n, fill = Year)) + geom_col(position = "dodge") + coord_flip() + labs(x = "研究方向", y = "数量", fill = "年级") + theme_minimal()
内容的提问来源于stack exchange,提问作者Alessia
相关产品推荐
相关产品推荐

