This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Delete columns with specific headers in a dataframe in R

Hi, I have a data frame containing 2000 columns. All columns have "X111, X222....." as their headers except a few. I want to retain only the ones containing "X..." and delete all the others. Also, I need rows containing only "rsids".
How should I do this in R ? Thanks for your help in advance.

r dataframes

1 answer

using grep

df <- df[,grep(pattern="^X",colnames(df)] # filter on columns using regexp "^X" 
df <- df[grep(pattern="rsids",row.names(df),] # filter on rows using "rsids" pattern

of course you could do it in one step :

 df <- df[grep(pattern="rsids",row.names(df),grep(pattern="^X",colnames(df)]

Hi! Thanks for your reply. I have one thing to clarify. Here, when you use it on the same df, will the output remain as a data frame or changes to values ? When I used this, My data frame was converted to a variable containing values.

it remains a data.frame but will overwrite the original data.frame

you could write this to keep the original df and save a new df (df.filter):

df.filter <- df[grep(pattern="rsids",row.names(df),grep(pattern="^X",colnames(df)]

Used the same code, I am not sure where I am going wrong but didn't work. It moved to the values environment with a variable containing values showing "int [1:2305] 1 2 3 ...."

could you do is(df) . change df to the name of your data.frame.

Ofcourse, I did chang df to my dataframe's name. Will check if this works. Thanks!

is(df) is just to know the type of the object

Log in to answer this question.