costebk08
costebk08

Reputation: 1359

specifying column name when one column is selected using grep in r

I am having an issue with the grep function. Specifically, when I tell R to get all the columns that start with a certain letter using the function, and there is only one such column, all that is yielded is the data with the code as the column name like this:

> head(newdat1)
  i1 b2 b1 b17
1  1  1  2   0
2  1  1  2   0
3  1  1  2   0
4  1  1  2   0
5  2  1  1   0
6  3  1  1   1

datformeanfill<-as.data.frame(newdat1[,grep("^i", colnames(newdat1))])
> head(datformeanfill)
newdat1[, grep("^i", colnames(newdat1))]
1                                        1
2                                        1
3                                        1
4                                        1
5                                        2
6                                        3

As opposed to if I have two or more columns that start with the same letter:

datnotformeanfill<-as.data.frame(newdat1[,grep("^b", colnames(newdat1))])
> head(datnotformeanfill)
    b2 b1 b17
  1  1  2   1
  2  1  2   1
  3  1  2   1
  4  1  2   1
  5  1  1   1
  6  1  1   2

Where we see the column names are maintained, and it does the same if I have multiple "i". Please help thanks!

Upvotes: 0

Views: 77

Answers (1)

MrFlick
MrFlick

Reputation: 206232

Use

datformeanfill <- newdat1[,grep("^i", colnames(newdat1)), drop=FALSE]

to ensure you always get back a data.frame. See ?'[.data.frame' for the details.

Upvotes: 2

Related Questions