[R] learning R

Petr PIKAL petr.pikal at precheza.cz
Wed Feb 25 09:48:51 CET 2009


Hi

r-help-bounces at r-project.org napsal dne 25.02.2009 06:18:04:

> Hi Ira:
> 
> For your first question, under the hood of R, names<- is actually a 
> function so , when you do that, you need to say names(a)[2] rather
> than names(a[2]). why this is is tricky and I wouldn't do it justice if 
> i tried to explain it. it's best if you do ?"names<-" at an R prompt and 

> read that.
> 
> For the second one, you can rbind x with anything that of length one and 

> the recycling concept in R will add the extra now but maybe there's a 
> better way that someone else will hopefully send.
> 
> 
> 
#==================================================================================
> 
> a=c(1,2)
> names(a)=c("one","two")
> names(a[2])
> names(a)[2]<-"too"
> names(a)
> 
> 
> 
#===================================================================================
> 
> x=c(1,2,3)
> y=c(3,4,5)
> 
> x <- matrix(x,nrow=1)
> print(x)
> x <- rbind(x,NA)
> x[2,] <- y
> print(x)

I can not resist to point out difference between matrices and data frames. 
For those who work with R are obvious but for newcomer using rbind or 
especially cbind with matrices or data frames can lead to nasty surprise 
when adding non numeric column to numeric matrix or values to data frame 
which have different type.

See appropriate help page for rbind.

Regards
Petr

> 
> 
> 
> On Tue, 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"?
> >
> > 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
> >
> > ______________________________________________
> > 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.
> 
> ______________________________________________
> 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