简体   繁体   中英

Extracting elements from List in R

I am a beginner in R. So I am experimenting with lists to understand R. x <- list(foo = 1:4, bar = 0.6) I am able to get the foo variable from x with y = x[1] . x and y both are lists and I can get the first element from x with x[1] but it is not possible to get the first element from y with y[1] . y[1] is giving $foo [1] 1 2 3 4 What are the differences between x and y here?

R can be confusing in this regard. The problem is that x[1] gives you a list, not the values stored in the first element of the list.

Suppose x <- list(foo = 1:4, bar = 0.6) , you can extract from x in two ways

You can subset by the index: x[[1]] will give you the values in the first vector while x[1] will give you a list containing the first list in x

> x[[1]]
[1] 1 2 3 4

> x[1]
$foo
[1] 1 2 3 4

Beside x[[1]] , you can subset x by the name that you assigned, namely,

> x$foo
[1] 1 2 3 4

The reason y = x[1] doesn't work is because you're not assigning the vector of values 1 to 4 to y , you're passing a list. so y is a list of length 1. Consequently, you wish to do

y=x[[1]]

or

y=x$foo

This way, you can subset y as you desire:

> y[1]
[1] 1

HOWEVER, with you current method y = x[1] , y is a list, therefore, you can subset the y like you would a normal list:

> y[[1]][1]
[1] 1

or

> y$foo[1]
[1] 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM