Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to access list elements in R [duplicate]

Tags:

list

dataframe

r

I am trying to make a list and access it's cells later in R. I am new to R and have a Matlab background. These [], [[]] are really bugging me. I tried reading the help and online but I still don't get it. In the following code c["var1"][1] returns differently than c$"var"[1].

What are the actual uses for these three notations [], [[]], $?

v <- vector("character", 5)
v[1] <- 'a'
v[2] <- 'a'
v[4] <- 'a'
v
# [1] "a" "a" ""  "a" "" 
c <- list(v, v)
names(c) <- c("var1", "var2")
c
# $var1
# [1] "a" "a" ""  "a" "" 

# $var2
# [1] "a" "a" ""  "a" "" 

c["var1"][1]
# $var1
# [1] "a" "a" ""  "a" "" 

c$"var1"[1]
# [1] "a"
like image 542
bytestorm Avatar asked Sep 28 '15 09:09

bytestorm


People also ask

How do you access the elements of a list in R?

A list in R is created with the use of list() function. R allows accessing elements of a list with the use of the index value.

How do I access the nested list in R?

You can access individual items in a nested list by using the combination of [[]] or $ operator and the [] operator.

Can list contain another list R?

The list data structure in R allows the user to store homogeneous (of the same type) or heterogeneous (of different types) R objects. Therefore, a list can contain objects of any type including lists themselves.

What is a list explain the concept of lists in R with examples?

In R, lists are the second type of vector. Lists are the objects of R which contain elements of different types such as number, vectors, string and another list inside it. It can also contain a function or a matrix as its elements. A list is a data structure which has components of mixed data types.


1 Answers

All these methods give different outputs

[ ] returns a list

[[ ]] returns the object which is stored in list

If it is a named list, then

List$name or List[["name"]] will return same as List[[ ]]

While List["name"] returns a list, Consider the following example

> List <- list(A = 1,B = 2,C = 3,D = 4)
> List[1]
$A
[1] 1

> class(List[1])
[1] "list"
> List[[1]]
[1] 1
> class(List[[1]])
[1] "numeric"
> List$A
[1] 1
> class(List$A)
[1] "numeric"
> List["A"]
$A
[1] 1

> class(List["A"])
[1] "list"
> List[["A"]]
[1] 1
> class(List[["A"]])
[1] "numeric"
like image 195
Koundy Avatar answered Sep 21 '22 12:09

Koundy