[R] For loop into a vectorized form?

jim holtman jholtman at gmail.com
Sat Jan 30 20:46:02 CET 2010


Is this what you want:

> mylist <- list(a = letters[1:3], b = LETTERS[1:3], c = c("1", "2", "3"))
>
> x <- expand.grid(seq(length(mylist$a)), seq(length(mylist$b)))
> result <- apply(x, 1, function(.row){
+     list(mylist[[1]][.row[1]], mylist[[2]][.row[2]], mylist[[3]])
+ })
>
> result
[[1]]
[[1]][[1]]
[1] "a"

[[1]][[2]]
[1] "A"

[[1]][[3]]
[1] "1" "2" "3"


[[2]]
[[2]][[1]]
[1] "b"

[[2]][[2]]
[1] "A"
...........


On Fri, Jan 29, 2010 at 9:31 AM, johannes rara <johannesraja at gmail.com> wrote:
> 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"
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list