[R] Plot a series of plots without using a loop

Rui Barradas ruipbarradas at sapo.pt
Wed Jul 31 10:35:42 CEST 2013


Hello,

There's a bug in the line

for (i in 1:length(dim(somdata.xyf$codes$X)[2]))

length() is always 1, you can use simply 1:dim(...)[2] or even simpler

for(i in 1:ncol(somdata.xyf$codes$X))

As for a way without a loop, you could use ?sapply:

sapply(1:ncol(somdata.xyf$codes$X), function(i) plot(...))

But I believe the loop is far more readable, and preferable.

Rui Barradas

Em 31-07-2013 00:25, Ben Harrison escreveu:
> On 30 July 2013 21:35, Rui Barradas <ruipbarradas at sapo.pt> wrote:
>> Hello,
>>
>> Maybe the following does it.
>>
>> op <- par(mfrow=c(2, 3))
>>
>> for(i in 1:6){
>>          plot(somdata.xyf,
>>               type="property",
>>               property=somdata.xyf$codes$X[, i],
>>               main=colnames(somdata.xyf$codes$X)[i])
>> }
>>
>> par(op)
>>
>>
>> Hope this helps,
>>
>> Rui Barradas
>
> Thanks Rui,
> that does it for sure. I had come to that solution, but just realised
> by looking at it again, I could change
> for (i in 1:6)
> with
> for (i in 1:length(dim(somdata.xyf$codes$X)[2]))
>
> I was also wondering if there was a way to do it without a for loop,
> but in this case it's a very small number of iterations, so probably
> not worth it.
>
> Ben
>



More information about the R-help mailing list