根据R

时间:2017-07-14 12:45:57

标签: r regex list

我需要根据单独的源列表计算列表中单词或单词短语出现的频率  我有一个作者和研究领域的数据框架。每位作者都有一个与其姓名相关的一个或多个研究领域(单词/单词短语)的列表  有时相同的研究领域不止一次出现,我希望每次都计算它们(即,不是唯一的列表)  我需要计算一个作者的研究领域与研究领域列表中的研究领域相匹配的次数  我可以在每个作者的基础上进行,但不能用于整个作者列表  (实际上,有4个集合列表,分为研究类别:生命科学,社会科学等,我需要计算每个研究类别中每位作者的研究领域的发生情况,即生命科学领域有多少他们的名单,列表中有多少社会科学领域等。  下面是一个研究类别的简单示例,但在实际示例中,有4个独立且独特的词典'。

test.small <- data.frame(AuthorID=c("Mavis", "Cleotha", "Yvonne"), 
                     RA=c("Fisheries, Fisheries, Geography, Marine Biology", "Fisheries", 
                          "Marine Biology, Marine Biology, Fisheries, Zoology"))
RA.text <- as.character(test.small$RA)
RA.list <- strsplit(RA.text, ", ", perl=TRUE)
lexicon <- c("Fisheries", "Marine Biology")

sum(RA.list[[3]] %in% lexicon)

如何对整个列表执行此操作,将每个作者的总出现次数相加  并将该数字和存储在我可以用于其他计算的向量中?

2 个答案:

答案 0 :(得分:1)

您可以创建一个函数,并使用lapply将该函数应用于所有行。如果我理解你的问题,以下内容适用于我:

test.small <- data.frame(AuthorID=c("Mavis", "Cleotha", "Yvonne"), 
                         RA=c("Fisheries, Fisheries, Geography, Marine Biology", "Fisheries", 
                              "Marine Biology, Marine Biology, Fisheries, Zoology"))

frequency_counter <- function(x,lexicon)
{
x<- as.character(x)
RA.list <- strsplit(x, ", ", perl=TRUE)
count = sum(RA.list[[1]] %in% lexicon)
return(count)
}

# apply the function
lexicon <- c("Fisheries", "Marine Biology")
test.small$count = lapply(test.small$RA,function(x) frequency_counter(x,lexicon))

答案 1 :(得分:1)

我们可以使用str_count包中的stringr。在以下示例中,test.small2是一个数据框,其中Count列显示了单词计数。

请注意,我在创建stringsAsFactors = FALSE时添加了test.small,以确保所有列都是字符,而不是因素。

or1rebus包中的函数,它创建正则表达式语法|

使用str_count,我们可能不需要strsplit字符串。

# Create example data frame
test.small <- data.frame(AuthorID=c("Mavis", "Cleotha", "Yvonne"), 
                         RA=c("Fisheries, Fisheries, Geography, Marine Biology", "Fisheries", 
                              "Marine Biology, Marine Biology, Fisheries, Zoology"),
                         stringsAsFactors = FALSE)

# Load packages
library(dplyr)
library(stringr)
library(rebus)

# Define the lexicon
lexicon <- c("Fisheries", "Marine Biology")

# Create a new column showing the total number of words matching the lexicon
test.small2 <- test.small %>% mutate(Count = str_count(RA, or1(lexicon)))