如何计数单元格中由逗号分隔的唯一的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包来回答这个问题,但只能让它计数唯一的单词,而不是唯一的属种

短语。
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包(v2.0.1)于2018-10-04创建

我们可以使用separate_rowscount

library(dplyr)
library(tidyr)
df1 %>% 
separate_rows(Spp, sep = ",\s+") %>%
count(Spp, name = 'Freq')
# A tibble: 3 × 2
Spp              Freq
<chr>           <int>
1 Genus1 species1     3
2 Genus1 species2     2
3 Genus2 species1     1

最新更新