[R] For loop into a vectorized form?
johannes rara
johannesraja at gmail.com
Fri Jan 29 15:31:28 CET 2010
How to vectorize this for loop and how can I assign result to vector
instead of using print function?
mylist <- list(a = letters[1:3], b = LETTERS[1:3], c = c("1", "2", "3"))
for (i in seq_along(mylist[[1]])) {
for (j in seq_along(mylist[[2]])) {
print(mylist[[1]][i])
print(mylist[[2]][j])
print(mylist[[3]])
}
}
Run version:
> mylist <- list(a = letters[1:3], b = LETTERS[1:3], c = c("1", "2", "3"))
> mylist
$a
[1] "a" "b" "c"
$b
[1] "A" "B" "C"
$c
[1] "1" "2" "3"
> for (i in seq_along(mylist[[1]])) {
+ for (j in seq_along(mylist[[2]])) {
+ print(mylist[[1]][i])
+ print(mylist[[2]][j])
+ print(mylist[[3]])
+ }
+ }
[1] "a"
[1] "A"
[1] "1" "2" "3"
[1] "a"
[1] "B"
[1] "1" "2" "3"
[1] "a"
[1] "C"
[1] "1" "2" "3"
[1] "b"
[1] "A"
[1] "1" "2" "3"
[1] "b"
[1] "B"
[1] "1" "2" "3"
[1] "b"
[1] "C"
[1] "1" "2" "3"
[1] "c"
[1] "A"
[1] "1" "2" "3"
[1] "c"
[1] "B"
[1] "1" "2" "3"
[1] "c"
[1] "C"
[1] "1" "2" "3"
>
More information about the R-help
mailing list