R List Tutorial

How to create a list in R

Creating a list in R is very easy. Just use list() function. Let us create a dummy list.

In [1]:
c <- list("a b c")

To check if it is a list. just typeof(c)

In [2]:
typeof(c)
'list'

We can also find out how elements inside list are stored. Use the str() function.

In [3]:
str(c)
List of 1
 $ : chr "a b c"

As we see above, 'a b c' are not stored at different characters but as one character. Therefore when we access list element. We would get 'a b c' as one element. Let us try this.

How to access elements in R list

To access element in list, we can simply index it.

In [4]:
c[1]
  1. 'a b c'

Two things. Firstly notice, indexing starts with 1 and indexed element is 'a b c'. That is how it is stored in the list.

If we want to store a,b and c as separate elements. We should use comma not space as shown below.

In [5]:
l1 <- list("a","b",'c')

Now if do str(x), it should show us 3 different characters.

In [6]:
str(l1)
List of 3
 $ : chr "a"
 $ : chr "b"
 $ : chr "c"

Let us try to access the first element now, we should get character 'a'

In [7]:
l1[1]
  1. 'a'

How to add elements to list in R

To add elements, we need to use double square brackets and assign the value. Let us say we want to add at location 4.

In [8]:
l1[[4]] = 1

Now let us check our list. It should have 4 elements.

In [9]:
l1
  1. 'a'
  2. 'b'
  3. 'c'
  4. 1

What happens if try to add at position 6. You can still do that even though list has data only in first 4 locations. It will automatically assign null values in the intermediate locations. Let us try that.

In [10]:
l1[[6]] = 5
In [11]:
l1
  1. 'a'
  2. 'b'
  3. 'c'
  4. 1
  5. NULL
  6. 5
In [12]:
str(l1)
List of 6
 $ : chr "a"
 $ : chr "b"
 $ : chr "c"
 $ : num 1
 $ : NULL
 $ : num 5

As we see above, index 5 has NULL data type.

How about overwriting the data at existing location. Let us try that replacing the data at location 1.

In [14]:
l1[1] = "John"
In [15]:
l1
  1. 'John'
  2. 'b'
  3. 'c'
  4. 1
  5. NULL
  6. 5

Note, we can use single square bracket too while overwriting the value in list as shown above.. The value at location 1 is changed to "John"

Lists are very flexible in R. We can store values as key value pairs. So instead of accessing the elements using index, we can access through key. Let us add a new value to our list. This time we will assign a key to a value in our list.

In [16]:
l1[["name"]] = "Alex"

Ok let us print now the contents of our list.

In [17]:
l1
[[1]]
'John'
[[2]]
'b'
[[3]]
'c'
[[4]]
1
[[5]]
NULL
[[6]]
5
$name
'Alex'

As we see above, for our last entry, a key ("name") has been added. We can access our element "Alex" now using the key "name".

In [18]:
l1$name
'Alex'

That is convenient. Let us now access the element at first location again.

In [19]:
l1[1]
$NA = 'John'

Ok we see now that output as $NA = 'John'. This tells us that data structure of list has changed. Now every value should have ideally a key.

We can find out the keys by using names() method.

In [20]:
names(l1)
  1. ''
  2. ''
  3. ''
  4. ''
  5. ''
  6. ''
  7. 'name'

As we see above, we dont have keys for the 4 entries in our list. We can assign the keys easily. Let us do that for our ist element.

In [21]:
names(l1)[1] <- 'v1'
In [23]:
l1
$v1
'John'
[[2]]
'b'
[[3]]
'c'
[[4]]
1
[[5]]
NULL
[[6]]
5
$name
'Alex'

As we see above element in location 1 has key 'v1' now. We can access data at location 1 using key v1 as shown below.

In [24]:
l1$v1
'John'

How to convert list to CSV in R

csv is popular data format. Often times we need to write our data in csv format. We can easily do that in R. One of the easiest ways is to convert our list first to dataframe and then we can write out dataframe in csv format using write.csv function.

In [26]:
df <- data.frame(l1,row.names = F)

Well, I got the following error... Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 1, 0

The reason for that is we have null data in our list. We need to remove it first.

In [27]:
l1 <- l1[-5]

with l1[-5] we took out the data at location 5. Let us check that.

In [28]:
l1
$v1
'John'
[[2]]
'b'
[[3]]
'c'
[[4]]
1
[[5]]
5
$name
'Alex'

Now we should be able to convert our list to R dataframe.

In [29]:
df <- data.frame(l1)
In [30]:
head(df)
A data.frame: 1 × 6
v1X.b.X.c.X1X5name
<fct><fct><fct><dbl><dbl><fct>
1Johnbc15Alex

Now let us write our dataframe to CSV using write.csv function as shown below.

In [31]:
write.csv(df,'MyData.csv',row.names = FALSE)

I am in Unix, so let us use the cat command to see the contents our csv file.

In [32]:
system('cat MyData.csv | head -2',intern=TRUE)
  1. '"v1","X.b.","X.c.","X1","X5","name"'
  2. '"John","b","c",1,5,"Alex"'

How to remove elements in list in R

Removing a list element in R is very easy. Just assign that value to null. Let us say we want to remove element at location at 1.

In [33]:
l1$v1 <- NULL
In [34]:
l1
[[1]]
'b'
[[2]]
'c'
[[3]]
1
[[4]]
5
$name
'Alex'

Another easy way is negative indexing. Let us say we want to remove the element at location 3, we can use negative indexing li[-3] as shown below.

In [35]:
l2 <- l1[-3]
In [36]:
l2
[[1]]
'b'
[[2]]
'c'
[[3]]
5
$name
'Alex'

How to loop through list in R

In [37]:
for (e in l1) {
  print(e)
}
[1] "b"
[1] "c"
[1] 1
[1] 5
[1] "Alex"

How to check the length of list in R

In [38]:
length(l1)
5

Wrap Up!

I hope you would find this tutorial useful.