r - 如何计算 R 中单元格内由逗号分隔的唯一 2 个单词短语?
问题描述
我有一个不同位置的数据框 ( ) 以及在每个位置发现Location
的动物种类 ( )。Spp
动物的物种使用其独特的属物种名称进行编码。我想知道每个独特的属物种在数据框中的频率。
示例数据
df1 <- data.frame(matrix(ncol = 2, nrow = 3))
x <- c("Location","Spp")
colnames(df1) <- x
df1$Location <- seq(1,3,1)
df1[1,2] <- c("Genus1 species1")
df1[2,2] <- c("Genus1 species1, Genus1 species2")
df1[3,2] <- c("Genus1 species1, Genus1 species2, Genus2 species1")
输出应该是这样的
Spp Freq
Genus1 species1 3
Genus1 species2 2
Genus2 species1 1
我已经尝试使用该corpus
软件包来回答这个问题,但只能让它计算唯一的单词而不是唯一的Genus 物种短语。
library(tm)
library(corpus)
library(dplyr)
text <- df1[,2]
docs <- Corpus(VectorSource(text))
docs <- docs %>%
tm_map(removePunctuation)
dtm <- TermDocumentMatrix(docs)
matrix <- as.matrix(dtm)
words <- sort(rowSums(matrix), decreasing = TRUE)
words ### only provides count of unique individual Genus and species words. I want similar but need to keep Genus and species together.
解决方案
这是一个快速的解决方案:
df1 <- data.frame(matrix(ncol = 2, nrow = 3))
x <- c("Location","Spp")
colnames(df1) <- x
df1$Location <- seq(1,3,1)
df1[1,2] <- c("Genus1 species1")
df1[2,2] <- c("Genus1 species1, Genus1 species2")
df1[3,2] <- c("Genus1 species1, Genus1 species2, Genus2 species1")
table(unlist(strsplit(df1$Spp,', ')))
#>
#> Genus1 species1 Genus1 species2 Genus2 species1
#> 3 2 1
由reprex 包于 2021-10-04 创建(v2.0.1)
推荐阅读
- python - 下载文件并在响应中重定向
- javascript - 在 VueJS 中渲染 [object HTMLTableElement]
- php - Excel 使用 Codeigniter 中的 phpexcel 库生成和发送电子邮件
- sql-server - MS SQl 根据行中的值创建列
- typescript - “FileList”类型上不存在 TypeScript 属性“forEach”
- node.js - Nodejs,Electron,如何添加滚动条?
- c++ - 读取向量时向量下标超出范围
- php - 在 laravel 中删除有照片但没有照片的用户
- websocket - 使用 MQTT 协议时,诸如 Exchange 或 Queue 之类的 RabbitMQ 概念是否仍然有效?
- c# - Azure 文件挂载到云服务