# [R] Wrap a loop inside a function

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Wed Jul 19 22:17:09 CEST 2006

Doran, Harold wrote:
> I need to wrap a loop inside a function and am having a small bit of
> difficulty getting the results I need. Below is a replicable example.
>
>
> # define functions
> pcm <- function(theta,d,score){
>      exp(rowSums(outer(theta,d[1:score],'-')))/
>      apply(exp(apply(outer(theta,d, '-'), 1, cumsum)), 2, sum)
>    }
>
> foo <- function(theta,items, score){
>    like.mat <- matrix(numeric(length(items) * length(theta)), ncol =
> length(theta))
>    for(i in 1:length(items)) like.mat[i, ] <- pcm(theta, items[[i]],
> score[[i]])
>    }
>
> # begin example
> theta <- c(-1,-.5,0,.5,1)
> items <- list(item1 = c(0,1,2), item2 = c(0,1), item3 = c(0,1,2,3,4),
> item4 = c(0,1))
> score <- c(2,1,3,1)
> (foo(theta, items, score))
>
> # R output from function foo
> [1] 0.8807971 0.8175745 0.7310586 0.6224593 0.5000000
>
>
> However, what I am expecting from the function foo is
>
>
>>like.mat
>
>             [,1]       [,2]       [,3]       [,4]      [,5]
> [1,] 0.118499655 0.17973411 0.25949646 0.34820743 0.4223188
> [2,] 0.880797078 0.81757448 0.73105858 0.62245933 0.5000000
> [3,] 0.005899109 0.01474683 0.03505661 0.07718843 0.1520072
> [4,] 0.880797078 0.81757448 0.73105858 0.62245933 0.5000000
>
>
> I cannot seem to track down why the function foo is only keeping the
> last row of the full matrix I need. Can anyone see where my error is?
>
> Thanks,
> Harold
>
> platform       i386-pc-mingw32
> arch           i386
> os             mingw32
> system         i386, mingw32
> status
> major          2
> minor          3.0
> year           2006
> month          04
> day            24
> svn rev        37909
> language       R
> version.string Version 2.3.0 (2006-04-24)
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.

Hi, Harold,

Your function "foo" is only returning the last call from "for". Try:

foo <- function(theta,items, score){
like.mat <- matrix(numeric(length(items) * length(theta)),
ncol = length(theta))
for(i in 1:length(items))
like.mat[i, ] <- pcm(theta, items[[i]], score[[i]])
## return like.mat, not just the last line from "for"
like.mat
}

HTH,

--sundar