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.
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.
• 16,007 views
•
link
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)]
• 0 views
•
link
• 0 views
•
link
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)]
• 0 views
•
link
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 ...."
• 0 views
•
link
Log in to answer this question.