logo

Accessing Lists in R 📂R

Accessing Lists in R

Overview

R offers many great features for handling data, and among them, the list is one of the primary reasons for using R. Although list data types are implemented in many other languages like Python, none offer the ease and intuitive manipulation of data that R provides. Mastering the use of lists allows for handling tasks that would be more complex and tedious in other programming languages with ease.

Example

20190604\_161445.png

Consider a scenario where three sequences are part of a single list as shown above. By default, when you inspect the data, it is correct to refer to it as $이 있으면 데이터$name. However, if the name is too long and cumbersome to input each time, or when the code becomes complicated or requires repeated work, it isn’t feasible to write it out every single time.

20190604\_161526.png Fortunately, even when lists have designated names, they are still assigned numbers sequentially. Therefore, you can reference them by number as shown above.

20190604\_161541.png Referencing by number implies that you can also reference by variable. As shown above, it’s confirmed that even if a loop is written in this way, it runs smoothly.

However, there are times when dealing with variables by name is more convenient in loops, not numbers. For example, consider you have created a list with 40 types of weather data but want to exclude only “temperature” and “humidity.” In this case, techniques that involve creating an index for the strings are frequently used. Fortunately, lists accept both data$이름데이터$"name" the same, allowing for flexible code writing. Moreover, this isn’t the only functionality; data[[name]] is also possible. The $ symbol can be used in contexts other than lists, such as data frames, so to avoid confusion when handling complex data, it is recommended to use the [[]] symbol, which is exclusively for lists.

20190604\_161733.png

Code

sequence<-list(arithmetic=1:10,
               geometric=2^(1:10),
               alternative=1:10*rep(c(1,-1),5))
sequence
 
sequence$geometric
seqence[[2]]
 
for(i in 1:3){
  print(sum(sequence[[i]]))
}
 
sequence$"arithmetic"
for(i in c("arithmetic","alternative")){
  print(sequence[[i]])
}