Hack: The ‘[‘ in R lists

cupom com desconto - o melhor site de cupom de desconto cupomcomdesconto.com.br


[This article was first published on R – Predictive Hacks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)


Want to share your content on R-bloggers? click here if you have a blog, or here if you don’t.

Assume that you have a list and you want to get the n-th element of each component or generally to subset the list. You can use the command sapply(list, "[", c(1,2,3,..))

Let’s see this in practice.

mylist

Output:

cupom com desconto - o melhor site de cupom de desconto cupomcomdesconto.com.br
> mylist
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1] "m" "m" "m" "f" "f" "f" "m" "f" "f" "f"

[[3]]
 [1]  5 20 30 10 20 50  5 20 10 30

Let’s say that we want to get the 3rd and 6th element of the list:

sapply(mylist, "[", c(3,6))
 

Output:

     [,1] [,2] [,3]
[1,] "3"  "m"  "30"
[2,] "6"  "f"  "50"




cupom com desconto - o melhor site de cupom de desconto cupomcomdesconto.com.br
Leia Também  Uncanny X-Men: opinião bayesiana na análise do Dr. Silge