Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"No such index at level 1" syntax error in simple word locator function

Tags:

r

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)

The function is supposed to create a list with the key being the word and the values the locations of the words. The error I get is "No such index at level 1".

like image 1000
megashigger Avatar asked Jan 18 '26 22:01

megashigger


1 Answers

   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)
    }

This gives

$foo
[1] 1

$bar
[1] 2

$baz
[1] 3
like image 73
Scott C Wilson Avatar answered Jan 20 '26 16:01

Scott C Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!