[R] for loop problem

Prof Brian Ripley ripley at stats.ox.ac.uk
Sun Jan 21 15:49:03 CET 2007


On Sun, 21 Jan 2007, Uwe Ligges wrote:

> aat wrote:
>> Hello R users,
>>
>> A beginners question which I could not find the answer to in earler posts.
>>
>> My thought process:
>> Here "z" is a 119 x 15 data matrix
>> Step 1: start at column one, bind every column with column 1
>> Step2: use the new matrix, "test", in the fitCopula package
>> Step3: store each result in myfit, bind each result to "answer"
>> Step4: return "answer"
>>
>>
>> copula_est <- function(z)
>> {
>> 	for(i in 1:length(z[1,]))
>> 	{
>> 		my.cop <- normalCopula(param = 0.5, dim = 2)
>> 		test <- cbind(z[,1],z[,i])
>> 		myfit[i] <- fitCopula(test,my.cop, start=0.3)
>> 	}
>> 	answer <- cbind(myfit[i])
>> 	return(answer)
>> }
>
>
> The example is not reproducible for us, since we do not have z.

Nor is there a package 'fitCopula' available to us.

> I'd try to rewrite it as follows, without having tried anything:
>
> my.cop <- normalCopula(param = 0.5, dim = 2)
> answer <- apply(z[,-1], 2,
>    function(x) fitCopula(cbind(z[,1], x), my.cop, start=0.3),
>    my.cop = my.cop)

That is not quite the same thing, as he included i=1 in the loop.

Assuming this is package 'copula' the result is an S4 classed object 
(although that is far from clear on the help page).  apply() is not said 
to work with such functions (and I have little idea what as.vector will 
do, most likely fail), so I think I would use lapply().  Something like

answer <- lapply(seq_len(ncol(z)),
    function(i) fitCopula(cbind(z[,1], z[,i]), my.cop, start=0.3),
    my.cop = my.cop)

[...]

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list