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级没有这样的索引”。
答案 0 :(得分:3)
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
答案 1 :(得分:0)
在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