Yaron Nolan
Yaron Nolan

Reputation: 153

create a new data frame with columns from another data frame based on column names in R

Data frame A exists.

I want to create Data frame B and insert certain columns from data frame A in Data frame B.

I do not want to use the column numbers but the column names to do that

Thank you very much!!!!

Upvotes: 3

Views: 46405

Answers (1)

akrun
akrun

Reputation: 886938

We can use the subset of column names if there are no patterns

dataB <- dataA[, c("P1", "xyz", "acdc")]

Or if there are some sequence of column names based on index, subset the column names with a position index and use that to select the columns

dataB <- dataA[, colnames(dataA)[c(1,2,4,5,6,7,8,9,10,40,43,46,47,48,49)]]

To make this easier, all the sequence can be abbreviated with :

dataB <- dataA[, colnames(dataA)[c(1:2, 4:10, 40, 43, 46:49)]]

Upvotes: 4

Related Questions