[R] For loop into a vectorized form?
David Winsemius
dwinsemius at comcast.net
Sat Jan 30 21:34:28 CET 2010
On Jan 29, 2010, at 9:31 AM, johannes rara wrote:
> How to vectorize this for loop and how can I assign result to vector
> instead of using print function?
> as.vector( sapply(mylist$a, function(x)
sapply(mylist$b, function (y)
{ c(x, y, mylist[[3]]) }
) ) )
[1] "a" "A" "1" "2" "3" "a" "B" "1" "2" "3" "a" "C" "1" "2" "3" "b"
"A" "1" "2" "3" "b" "B" "1" "2"
[25] "3" "b" "C" "1" "2" "3" "c" "A" "1" "2" "3" "c" "B" "1" "2" "3"
"c" "C" "1" "2" "3"
You did say you wanted a vector, right?
--
David.
>
> 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.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list