magsd
magsd

Reputation: 35

How to copy multiple columns to a new dataframe in R

I have a data set (df2) with 400 columns and thousands of rows. The columns all have different names but all have either 'typeP' or 'typeR' at the end of their names. They are not ordered sequentially (eg. P,P,P,P,R,R,R,R) but randomly (P,P,R,R,R,P,R,P etc). I want to create a new data frame with just those columns whose names have 'type P' in their names.

I'm very new to R and so far I have only managed to find the positions of those columns using: grep("typeP",colnames(df2)). Any help would be appreciated!

Upvotes: 1

Views: 1251

Answers (1)

akrun
akrun

Reputation: 887128

After we get the index, we can use that to subset the initial dataset

df3 <- df2[grep("typeP",colnames(df2))]

Upvotes: 1

Related Questions