I have a file like this:
a1,a2,a3,b1,b2,b3
1,2,3,4,5,6
0,1,2,3,4,5
...
In interactive command-line R, I type
data<-read.table('file.txt', sep=',', header=TRUE)
I then want to get all the columns which start with the letter a. For this
particular file, I can the type:
data[1:3]
What if i don't know that the columns that start with 'a' are
columns 1-3?
Is there any command that will pick out the desired columns automatically?
What if i want to match a generic regular expression instead of just looking
at the first letter?
thanks very much,
Rnewb
--
View this message in context:
http://www.nabble.com/getting-variables-based-on-name-tp25725837p25725837.html
Sent from the R help mailing list archive at Nabble.com.
This turns out to be quite easy... Given:> head(data)inst a1 a2 a3 a4 a5 a6 a7 a8 escore 1 1 1 1 0 1 1 0 0 0 4 2 1 0 1 0 0 0 0 0 0 1 3 1 1 0 0 1 0 1 1 1 2 4 1 0 1 0 0 0 1 0 0 1 You can use grep on the names of the columns in data> # returns the column numbers of cols that begin with "a" > grep("^a", names(data))[1] 2 3 4 5 6 7 8 9> data[,grep("^a", names(data))]a1 a2 a3 a4 a5 a6 a7 a8 1 1 1 0 1 1 0 0 0 2 0 1 0 0 0 0 0 0 3 1 0 0 1 0 1 1 1 4 0 1 0 0 0 1 0 0 5 0 0 0 0 0 1 0 0 and, of course, you can use any regular expression you like. -Wil -- View this message in context: http://www.nabble.com/getting-variables-based-on-name-tp25725837p25725905.html Sent from the R help mailing list archive at Nabble.com. [[alternative HTML version deleted]]
This turns out to be quite easy... Given:> head(data)inst a1 a2 a3 a4 a5 a6 a7 a8 escore 1 1 1 1 0 1 1 0 0 0 4 2 1 0 1 0 0 0 0 0 0 1 3 1 1 0 0 1 0 1 1 1 2 4 1 0 1 0 0 0 1 0 0 1 You can use grep on the names of the columns in data> # returns the column numbers of cols that begin with "a" > grep("^a", names(data))[1] 2 3 4 5 6 7 8 9> data[,grep("^a", names(data))]a1 a2 a3 a4 a5 a6 a7 a8 1 1 1 0 1 1 0 0 0 2 0 1 0 0 0 0 0 0 3 1 0 0 1 0 1 1 1 4 0 1 0 0 0 1 0 0 5 0 0 0 0 0 1 0 0 and, of course, you can use any regular expression you like. -Wil -- View this message in context: http://www.nabble.com/getting-variables-based-on-name-tp25725837p25725951.html Sent from the R help mailing list archive at Nabble.com. [[alternative HTML version deleted]]
thanks very much for the quick and accurate response! Rnewb -- View this message in context: http://www.nabble.com/getting-variables-based-on-name-tp25725837p25726184.html Sent from the R help mailing list archive at Nabble.com.