[R] choosing multiple columns

arun smartpink111 at yahoo.com
Sat Aug 11 18:12:54 CEST 2012


HI,

Try this:

dat1<-as.data.frame(matrix(rnorm(50,5),ncol=10))
colnames(dat1)<-paste0("OFB",1:10)
#to select first 8 columns - easy method

dat1[,1:8]
#2nd method
wanted<-paste0("OFB",1:8)
dat1[,colnames(dat1)%in%wanted]

#3rd method
#regular expression to select 3rd, 5th columns
dat1[grep("[[:alnum:]][c(3,5)]",colnames(dat1))]

#     OFB3     OFB5
#1 6.378474 7.490392
#2 5.323282 4.728561
#3 5.415081 4.661548
#4 4.000541 5.286831
#5 3.598919 6.080370


dat2<-data.frame(dat1,CFB=rnorm(5,15))
#select columns having OFB as column name

dat2[grep("OFB",colnames(dat2))]
#select 4-8 columns

dat2[grep("[4-8]",colnames(dat2))]

 #    OFB4     OFB5     OFB6     OFB7     OFB8
#1 4.545049 7.490392 5.441275 3.433050 4.656184
#2 5.015531 4.728561 5.429073 5.268677 5.569176
#3 5.533485 4.661548 5.586189 4.694112 5.209213
#4 6.427448 5.286831 5.521572 4.036457 5.532234
#5 5.500054 6.080370 6.259925 3.946102 4.554102

Hope this helps.

A.K.







----- Original Message -----
From: Sachinthaka Abeywardana <sachin.abeywardana at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Saturday, August 11, 2012 7:59 AM
Subject: [R] choosing multiple columns

Hi all,

I have a data frame that has the columns OFB1, OFB2, OFB3,... OFB10.

How do I select the first 8 columns efficiently without typing each and
every one of them. i.e. I want something like:

a<-data.frame(initial_data$OFB1-10) #i know this is wrong, what would be
the correct syntax?

Thanks,
Sachin

    [[alternative HTML version deleted]]

______________________________________________
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