[R] learning R
David Winsemius
dwinsemius at comcast.net
Wed Feb 25 06:12:28 CET 2009
On Feb 24, 2009, at 11:36 PM, 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"?
I cannot tell you why, perhaps you are not actually working with the
names of a, but I can show you that:
> names(a)[2] <- "too"
> a[2]
too
2
> a
one too
1 2
And this is seen as well in the help page examples. The help page also
says the following, which I cannot understand:
It is possible to update just part of the names attribute via the
general rules: see the examples. This works because the expression
there is evaluated as z <- "names<-"(z, "[<-"(names(z), 3, "c2")).
>
> 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)
That is ok. Also effective would be:
z <- matrix( c(x,y), ncol=length(x) )
>
>
> 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
Not sure why you are trying to do that to x since it is a vector but
it can be done if you make it a matrix first. Take a look at these and
see if you can figure out what is happening:
> x <- matrix(x,2,3) # second and third arguments of matrix function
are nrow and ncol.
> x
[,1] [,2] [,3]
[1,] 1 3 2
[2,] 2 1 3
And then try:
> x = c(1,2,3)
> x <- matrix(x,2,3,byrow=TRUE)
> x
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 3
And now that x is a matrix, this will work:
> x[2,] <- y
> x
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 3 4 5
-- David Winsemius
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list