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.
c <- list("a b c")
To check if it is a list. just typeof(c)
typeof(c)
We can also find out how elements inside list are stored. Use the str() function.
str(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.
c[1]
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.
l1 <- list("a","b",'c')
Now if do str(x), it should show us 3 different characters.
str(l1)
Let us try to access the first element now, we should get character 'a'
l1[1]
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.
l1[[4]] = 1
Now let us check our list. It should have 4 elements.
l1
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.
l1[[6]] = 5
l1
str(l1)
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.
l1[1] = "John"
l1
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.
l1[["name"]] = "Alex"
Ok let us print now the contents of our list.
l1
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".
l1$name
That is convenient. Let us now access the element at first location again.
l1[1]
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.
names(l1)
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.
names(l1)[1] <- 'v1'
l1
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.
l1$v1
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.
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.
l1 <- l1[-5]
with l1[-5] we took out the data at location 5. Let us check that.
l1
Now we should be able to convert our list to R dataframe.
df <- data.frame(l1)
head(df)
Now let us write our dataframe to CSV using write.csv function as shown below.
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.
system('cat MyData.csv | head -2',intern=TRUE)
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.
l1$v1 <- NULL
l1
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.
l2 <- l1[-3]
l2
How to loop through list in R
for (e in l1) {
print(e)
}
How to check the length of list in R
length(l1)
Wrap Up!
I hope you would find this tutorial useful.
Related Notebooks
- Python IndexError List Index Out of Range
- Remove An Item From A List In Python Using Clear Pop Remove And Del
- How To Convert Python List To Pandas DataFrame
- How to Convert Python Pandas DataFrame into a List
- PyTorch Beginner Tutorial Tensors
- Python Pandas String To Integer And Integer To String DataFrame
- How To Drop One Or More Columns In Pandas Dataframe
- How To Install R Sparklyr H2O Tensorflow Keras On Centos
- Machine Learning Linear Regression And Regularization