[R] Help with "For" instruction

David Winsemius
2011-01-04T07:47:28Z

On Jan 4, 2011, at 1:00 AM, ADias wrote:

>
> Hi,
>
> I am having a problem in doing something similar to this example:
>
> Suppose I have this vector a, and from it I wish to create 5 other
> vector
> each one with less one value than what object a has
>
> So I have "a"
> a<-c(1,2,3,4,5)
>
> and I want
>
> a1 that shoud have (2,3,4,5)
> a2 that should have (1,3,4,5)
> a3 that should have (1,2,4,5)
> a4 that should have (1,2,3,5)
> a5 that should have (1,2,3,4)
>
> I have tried like this but with no luck
>
> For ( i in 1:5) {
> a<-c(1,2,3,4,5)
> a((i)<-a[-i]
> }
>
> Is there a way to do this?

Dan showed you a method using assign (since that is what is needed for
what you asked for) but you would get a more flexible result if you
used a structure that could be easily indexed such as a matrix or list:
 > A <- sapply(1:5, function(i) a[-i])
 > colnames(A) <- paste("a", 1:5, sep="")
 > A
      a1 a2 a3 a4 a5
[1,]  2  1  1  1  1
[2,]  3  3  2  2  2
[3,]  4  4  4  3  3
[4,]  5  5  5  5  4

So:
 > A[ ,"a1"]
[1] 2 3 4 5

>

--

David Winsemius, MD
West Hartford, CT