Looping over multiple lists with base R -
in python can this..
numbers = [1, 2, 3] characters = ['foo', 'bar', 'baz'] item in zip(numbers, characters): print(item[0], item[1]) (1, 'foo') (2, 'bar') (3, 'baz')
we can unpack tuple rather using index.
for num, char in zip(numbers, characters): print(num, char) (1, 'foo') (2, 'bar') (3, 'baz')
how can same using base r?
to in r-native way, you'd use idea of data frame. data frame has multiple variables can of different types, , each row 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 access each row using matrix notation, leaving index blank includes everything.
d[1,] ## numbers characters ## 1 1 foo
you can loop on rows of data frame whatever want do, presumably want more interesting 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
Comments
Post a Comment