首页 > 解决方案 > 如何计算 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.

标签: rcorpus

解决方案


这是一个快速的解决方案:

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)


推荐阅读