Sunday, September 13, 2009

R names in dataframe matching a string

To find out which variables in a R dataframe (called "part2") contain
the words "cat" do the following:
names(part2[,grep("cat",names(part2))])
This produces a list the names of the variables.
[1] "cat" "cat_1" "cat2"
However I would usually rather know the variable (column) number
corresponding to "cat". To do this:
grep("cat",names(part2))
This gives:
[1] 1 41 235
Obviously then
names(part2)[c(1,41,235)]
also gives:
[1] "cat" "cat_1" "cat2"

--

Michael O'Donovan
skype: maodonovan
tel: 0110218108
fax: 0865173354

1 comment:

  1. Hi all,

    Technically, a dataframe is R, a type of object. Less formally, a dataframe is a type of table where the typical use employs the rows as observations and the columns as variables. Thanks a lot.....

    ReplyDelete