R basics: accessing elements of an object
Because I remember things better when I explain them, and because accessing elements inside a list in R is just barely different enough from other programming languages I'm used to that it's throwing me off with false cognates a bit -- here's a brief tour on basic ways to access objects in an R list. This is elementary R, but I'm a novice R programmer taking notes for my own reference, so hey.
Note that the ">" at the start of some lines is the R prompt ("stuff you should type"), but that you shouldn't type the ">." Everything else is print output that R will display to you.
First we need to create a list which we'll call mylist
.
> mylist <- list(component = c(1,2,3))
mylist
is a super-simple list. Its contents look like this:
> mylist
$component
[1] 1 2 3
This list only has one element. It is named component
. (It also has one attribute, as Jerzy pointed out in the comments below -- the single attribute is called "names".)
> attributes(mylist)
$names
[1] "component"
We can access the element named component in a few ways:
> mylist["component"]
> mylist[1]
One uses the element name, the other uses the index number. Both of these return a list, which looks like this when it's printed out -- note the $component
at the top. Inside the list is a vector of 3 numbers.
$component
# [1] 1 2 3
If you want to reach inside the list and get the stuff inside -- in this case, that vector of 3 numbers -- you can do it two ways as well: with the attribute name or the index number.
> mylist$component
> mylist[[1]]
Both of them will return simply the vector -- it won't be wrapped in a list. Note how there's no $component
label at the top.
[1] 1 2 3
Since mylist$component
and mylist[[1]]
return whatever is inside this list, and in this case it is a vector, we can access elements in it just like any other vector.
> mylist$component[2]
> mylist[[1]][2]
And you'll simply get that second number in the vector.
[1] 2
I read on John Cook's "R langauge for programmers" that you can think of R lists as C-style structs. That's not too bad.
Side note: R typically gives you columns (for instance, mymatrix[1]
gives you the first column of mymatrix
), but if you throw a comma afterwards it'll give you rows. (For instance, mymatrix[1,]
gives you the first row of mymatrix
). You can combine these: mymatrix[c(1,2,3),c(1,2)]
gives you the first 3 rows of the first 2 columns of mymatrix
.