【发布时间】:2020-01-21 06:36:18
【问题描述】:
我正在尝试这个问题,其中我需要在给定的输入句子中找到最长的偶数单词,如果两个或多个单词是最长偶数长度的单词,则必须返回第一个出现的单词。
例如:如果“这是一首很棒的歌” 该函数应返回“this”,因为它是句子中第一个出现的最长偶数长度的单词。
这个问题之前被问过并使用 dplyr 回答过, Function in R that returns first word in a sentence that is having a length which is an even number & also longest even word
我想尝试使用我的代码:
下面是我的代码:
sentence <- function(ip_sen) {
sentence_split <- strsplit(ip_sen, split = ' ')[[1]] #splitting the sentence into words
word_lengths_vector <- vector() #empty vector to store even length words
for (word in sentence_split) {
word_split <- strsplit(word, split = '')[[1]] #splitting each word
word_length <- length(word_split)
if (word_length %% 2 == 0) { # checking if the word is even
word_lengths_vector <- c(word_lengths_vector, word) #adding such words to the empty vector
}
}
for (w in 1:(length(word_lengths_vector)-1)) { #finding the longest word
if (nchar(word_lengths_vector[w]) > nchar(word_lengths_vector[w+1])) {
word_lengths_vector <- word_lengths_vector[-(w+1)] #removing smaller length words
}
}
word_lengths_vector[1] #returning the first word in the vector which will be the first occurring longest word
}
sentence('this is a great song')
但我遇到以下错误:
if (nchar(word_lengths_vector[w]) > nchar(word_lengths_vector[w +
: 需要 TRUE/FALSE 的缺失值
谁能告诉我如何解决这个问题?
【问题讨论】: