Ein eingebundener Text mit undefiniertem Zeichensatz wurde abgetrennt. Name: nicht verf?gbar URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20120130/080e7142/attachment.pl>
Le lundi 30 janvier 2012 ? 08:30 +0100, David Studer a ?crit :> Hello, > I have the following question: > > when creating a data.frame > a1<-c(1,2,3) > a2<-c(1,2,3) > c<-data.frame(a1,a2) > I can select columns using an index like: > c[,1:2] > Is this possible too when using column-names? (something like c(,"a1":"a2"), > which doesn't work)Read the R intro, or any tutorial on R. You can just do: c[,c("a1", "a2")] (And I think you don't understand what ":" does, read the manual. At least, it doesn't work like your attempt c(,"a1":"a2") would imply.)> Alternative question: Is there a function to get the index of a variable by > name or can I > select certain columns using a loop? (a_1, a_2, ..., a_n)No need for a loop: which(colnames(c) == "a1") Cheers
On Jan 30, 2012, at 2:30 AM, David Studer wrote:> Hello, > I have the following question: > > when creating a data.frame > a1<-c(1,2,3) > a2<-c(1,2,3) > c<-data.frame(a1,a2) > I can select columns using an index like: > c[,1:2] > Is this possible too when using column-names? (something like > c(,"a1":"a2"), > which doesn't work):Generally you need to use grep to convert column names to numbers for use within "[" operations] df[ , grep("^a1$", names(df)):grep"^"a2$", names(df)) ] -- Another David> > Alternative question: Is there a function to get the index of a > variable by > nameThat's what grep will do.> or can I > select certain columns using a loop? (a_1, a_2, ..., a_n) > > Thank you very much! > DavidDavid Winsemius, MD Heritage Laboratories West Hartford, CT