[R] learning R

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Feb 25 09:21:00 CET 2009


Fuchs Ira wrote:
> I was wondering why the following doesn't work:
>
> > a=c(1,2)
> > names(a)=c("one","two")
> > a
> one two
>   1   2
> >
> > names(a[2])
> [1] "two"
> >
> > names(a[2])="too"
> > names(a)
> [1] "one" "two"
> > a
> one two
>   1   2
>
> I must not be understanding some basic concept here.
> Why doesn't the 2nd name change to "too"?

because a[2] becomes a newly allocated vector once you make the
assignment, and so the assignment does not affect a.  however:

    names(a)[2] = 'too'
   
will affect a the way you seem to wish.

>
> also unrelated:  if I have two vectors and I want to combine them to
> form a matrix ,is cbind (or rbind) the most direct way to do this?
>
> e.g.
>
> x=c(1,2,3)
> y=c(3,4,5)
> z=rbind(x,y)
>
> alternatively: is there a way to make a matrix with dim=2,3 and then
> to replace the 2nd row with y
>
> something like this (which doesn't work but perhaps there is another
> way to do the equivalent?)
>
> attr(x,"dim")=c(2,3)
> x[2,]=y

you can do this:

    z = matrix(c(x, y), nrow=2, ncol=3, byrow=TRUE)

but rbind seems much simpler.

vQ




More information about the R-help mailing list