【发布时间】:2016-12-21 10:12:36
【问题描述】:
我正在使用下面的代码来计算给定句子中单词的出现次数
wordCount = function(sentence,word){
splitedVectorString <- c()
splitedVectorString <- strsplit(sentence," ")
count <- 0
for (j in splitedVectorString) {
print(length(splitedVectorString))
print(splitedVectorString)
print(word)
if (identical(word,j)) {
count <- count + 1
print(count)
}
}
}
程序运行成功,但计数为 0。我在控制台上将此函数称为
wordCount("This is XYZ and is running late","is")
当我打印分割向量 splitedVectorString 的长度时,它给了我 1。我在分割句子时遇到问题了吗?
确切地说,我不知道出了什么问题。我刚开始学习 R 编程
【问题讨论】:
-
你可能想读this question,它几乎是一样的(它带有一个向量,但使用
strsplit你可以将你的句子转换成一个向量)。 -
尝试使用 length(grep(word,sentence)) 但仍然得到 1 作为输出。我检查了 splatted 向量的长度,它给了我 1。为什么 splatted 向量“splitedVectorString”给出长度为 1。因此它没有迭代整个向量并且 for 循环只执行一次
-
使用
length(grep("\\<is\\>", strsplit("This is XYZ and is running late", " ")[[1]])) -
或者类似
sum(sapply(strsplit(sentence," ")[[1]], identical, y = word))(更接近你的功能)
标签: r