[英]“No such index at level 1” syntax error in simple word locator function
string <- "This is a test"
find_words_2 <- function(x){
words <- strsplit(x, " ")
l <- list()
for (i in 1:length(words)) {
wrd <- words[[i]]
l[[wrd]] <- c(l[[wrd]], i)
}
return(l)
}
find_words_2(string)
該功能應該創建一個列表,鍵為單詞,而值為單詞的位置。 我得到的錯誤是“在1級沒有這樣的索引”。
words <-"foo bar baz"
find_words_2 <- function(x){
words <- strsplit(x, " ")
l <- list()
for (i in 1:length(words[[1]])) {
wrd <- words[[1]][i]
l[[wrd]] <- c(l[[wrd]], i)
}
return(l)
}
這給
$foo
[1] 1
$bar
[1] 2
$baz
[1] 3
添加一個unlist以進行適當的作用域設置,否則您將解析一個長度為1的列表
find_words_2 <- function(x){
words <- strsplit(x, " ")
l <- list()
for (i in 1:length(unlist(words))) {
wrd <- unlist(words)[i]
l[[wrd]] <- c(l[[wrd]], i)
}
return(l)
}
R> x <- "fake text that I am using"
R> find_words_2(x)
$fake
[1] 1
$text
[1] 2
$that
[1] 3
$I
[1] 4
$am
[1] 5
$using
[1] 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.