Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over multiple lists with base R

Tags:

r

In python we can do this..

numbers = [1, 2, 3]
characters = ['foo', 'bar', 'baz']

for item in zip(numbers, characters):
    print(item[0], item[1])

(1, 'foo')
(2, 'bar')
(3, 'baz')

We can also unpack the tuple rather than using the index.

for num, char in zip(numbers, characters):
    print(num, char)

(1, 'foo')
(2, 'bar')
(3, 'baz')

How can we do the same using base R?

like image 710
spies006 Avatar asked Sep 13 '17 19:09

spies006


People also ask

Can you loop through multiple lists?

Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.

Can you loop through a list in R?

A for-loop is one of the main control-flow constructs of the R programming language. It is used to iterate over a collection of objects, such as a vector, a list, a matrix, or a dataframe, and apply the same set of operations on each item of a given data structure.

How do I loop through an array in R?

To iterate over items of a vector in R programming, use R For Loop. For every next iteration, we have access to next element inside the for loop block.


1 Answers

To do something like this in an R-native way, you'd use the idea of a data frame. A data frame has multiple variables which can be of different types, and each row is an observation of each variable.

d <- data.frame(numbers = c(1, 2, 3),
                characters = c('foo', 'bar', 'baz'))
d
##   numbers characters
## 1       1        foo
## 2       2        bar
## 3       3        baz

You then access each row using matrix notation, where leaving an index blank includes everything.

d[1,]
##   numbers characters
## 1       1        foo

You can then loop over the rows of the data frame to do whatever you want to do, presumably you actually want to do something more interesting than printing.

for(i in seq_len(nrow(d))) {
  print(d[i,])
}
##   numbers characters
## 1       1        foo
##   numbers characters
## 2       2        bar
##   numbers characters
## 3       3        baz
like image 67
Aaron left Stack Overflow Avatar answered Sep 20 '22 14:09

Aaron left Stack Overflow