简体   繁体   中英

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!!!!

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)]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM