R 向量中的字数计算

R 向量中的字数计算,r,R,目前我已经注册了一门R课程,其中一个练习是建立一个R程序来计算字符串中的单词。我们不能使用函数table,但必须使用常规方法返回字符串中最常用单词的输出。 i、 狐狸跳过圆锥体,然后。。。 因此,程序必须返回“the”,因为它是最流行的短语 到目前为止,我有以下几点: string_read<- function(phrase) { phrase <- strsplit(phrase, " ")[[1]] for (i in 1:length(phrase)){ p

目前我已经注册了一门R课程,其中一个练习是建立一个R程序来计算字符串中的单词。我们不能使用函数
table
,但必须使用常规方法返回字符串中最常用单词的输出。 i、 狐狸跳过圆锥体,然后。。。 因此,程序必须返回“the”,因为它是最流行的短语

到目前为止,我有以下几点:

string_read<- function(phrase) {

  phrase <- strsplit(phrase, " ")[[1]]
  for (i in 1:length(phrase)){
    phrase.freq <- ....
#if Word already exists then increase counter by 1

      }

string\u read您首先正确地将字符串拆分为单词,然后我们使用
sapply
循环每个单词,并对向量中的相似单词求和。我使用了
tolower
假设此操作不区分大小写

string_read<- function(phrase) {
   temp = tolower(unlist(strsplit(phase, " ")))
   which.max(sapply(temp, function(x) sum(x == temp)))
}

phrase <- "The fox jumped over the cone and the"

string_read(phrase)
#the 
#  1 

我们可以使用
str\u extract

library(stringr)
string_read<- function(str1) {
  temp <- tolower(unlist(str_extract_all(str1, "\\w+")))
  which.max(sapply(temp, function(x) sum(x == temp)))
}

phrase <- "The fox jumped over the cone and the"
string_read(phrase)
#the 
#  1 
phrase2 <- "The fox jumped over the cone and the fox, fox, fox, fox, fox"
string_read(phrase)
#fox 
# 2 
库(stringr)

string_readI我知道有人问过类似的变体,但它们倾向于使用表、库等,或者教学顾问排除的类似的变体。您了解R中的
列表
数据结构了吗?我认为它可以很好地存储每个单词的计数。我们简要介绍了它-我很高兴能够更深入地查看列表!我相信,除了矩阵结构之外,我们还讨论了这个问题。好吧,如果您还记得可以使用字符串设置和检索列表值,我认为您将有一个良好的开端,比如
count\u list[[“fox”]]=0;计数列表[[“福克斯”]]=计数列表[[“福克斯”]]]+1我明白了!但唯一的问题是,对于一个包含X多个元素的短语,我不能为每个排列创建一个列表,因为这样它就不可伸缩了?抱歉,如果我误解了。嗨Ronak,谢谢你的信息!我想试着了解你在这里做了什么。您已将字符串转换为小写操作,然后使用“”作为分隔符对其进行拆分。我只是查找了unlist,我看到它将列表转换为向量。但是,当您使用strsplit时,它不是已经矢量化了吗?@azurekirby基本上,
unlist
做的事情与
strsplit(短语“”[[1]]]
做的事情相同。它将
列表
转换为向量。但是如果你使用is.vector(短语),它将返回TRUE,那么当你使用unlist时,你不是正在对已经是向量的向量进行向量化吗?@azurekirby好的。所以
短语属于“字符”类,检查
类(短语)
,当我们做
strsplit(短语)”
它是一个列表时,检查
类(strsplit(phase)”
,所以当我们
取消列出
或做
[[1]
时,就像你的情况一样,我们将它转换为与原始的相同的类,即“字符”,检查
类(temp)
类(strsplit(短语“”[[1]])
但现在唯一的区别是它的长度,请检查
长度(短语)
长度(temp)
。希望它能澄清。谢谢Ronak。我和我的指导老师检查了这个问题,它能正常工作,但当我们尝试通过控制台线路调用它时。例如,短语Hi-Akrun,如果你再添加一系列单词,比如,fox,fox,fox,fox,fox-我认为它仍然将“the”注册为最常见的单词,这是不正确的。
library(stringr)
string_read<- function(str1) {
  temp <- tolower(unlist(str_extract_all(str1, "\\w+")))
  which.max(sapply(temp, function(x) sum(x == temp)))
}

phrase <- "The fox jumped over the cone and the"
string_read(phrase)
#the 
#  1 
phrase2 <- "The fox jumped over the cone and the fox, fox, fox, fox, fox"
string_read(phrase)
#fox 
# 2