LANGUAGE R: Error "Error in course[[1:98]] : recursive indexing failed at level 2" when trying to search the items in a list, how do I resolve?

Asked

Viewed 124 times

3

I have a "course" list in R, it consists of 98 items, each item has one or two variables of type Character. I want all the first variables of each item in the list, but when typing the command:

course[[1:98]][1]

I get the following error in the console: Error in travel[[1:98]] : recursive indexing failed at level 2

I have no idea what it is, the syntax I used seems to be the right one, nor is it anything complex. I’m very frustrated with it, can help me?

2 answers

5


[[ ]] only returns individual values, usually if using an integer or a string with it.

If you pass a vector it looks recursively. X[[1:2]] is the same as X[[1]][[2]]. That’s why he gave his recursion error.

In R you can do your operation with a for or a function such as apply:

teste <- list(
  a1 = list("a", "b"),
  a2 = list("a", "c"),
  a3 = list("a", "d"),
  a4 = list("a", "e")
)


novo_teste <- list()
for(i in 1:length(teste)){
  novo_teste[[i]] <- teste[[i]][[2]]
}
novo_teste
#> [[1]]
#> [1] "b"
#> 
#> [[2]]
#> [1] "c"
#> 
#> [[3]]
#> [1] "d"
#> 
#> [[4]]
#> [1] "e"

lapply(teste, function(x) x[[2]])
#> $a1
#> [1] "b"
#> 
#> $a2
#> [1] "c"
#> 
#> $a3
#> [1] "d"
#> 
#> $a4
#> [1] "e"

Created on 2020-06-12 by the reprex package (v0.3.0)

  • 1

    The operator [ acts as a function, can pass it directly to *apply: lapply(teste, "[[", 2)

4

You can use the tidyverse map function in some ways

library(tidyverse)

teste <- list(
  a1 = list("a", "b"),
  a2 = list("a", "c"),
  a3 = list("a", "d"),
  a4 = list("a", "e")
)

teste %>%
  map(~ .x[[2]])
#> $a1
#> [1] "b"
#> 
#> $a2
#> [1] "c"
#> 
#> $a3
#> [1] "d"
#> 
#> $a4
#> [1] "e"


teste %>%
  map(2)
#> $a1
#> [1] "b"
#> 
#> $a2
#> [1] "c"
#> 
#> $a3
#> [1] "d"
#> 
#> $a4
#> [1] "e"

teste %>%
  map(~ pluck(.x, 2))
#> $a1
#> [1] "b"
#> 
#> $a2
#> [1] "c"
#> 
#> $a3
#> [1] "d"
#> 
#> $a4
#> [1] "e"

# se vc pricisar de characters use map_chr

teste %>%
  map_chr(2)
#>  a1  a2  a3  a4 
#> "b" "c" "d" "e"

Created on 2020-06-12 by the reprex package (v0.3.0)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.