HaagenDaz
HaagenDaz

Reputation: 461

how to search for column names in a dataframe

I have the following data frame df2 and a vector n. How can I create a new data frame where df2 column names are same as vector n

df2 <- data.frame(x1=c(1,6,3),x2=c(4,3,1),x3=c(5,4,6),x4=c(7,6,7))
n<-c("x1","x4")

Upvotes: 0

Views: 119

Answers (2)

cseKostas
cseKostas

Reputation: 13

df3 <- subset(df2, select=c("x1", "x4"))
df3

hope it helps

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 270195

Any of these would work:

df2[n]

df2[, n] # see note below for caveat

subset(df2, select = n)

Note that in the second one if n can be of length one, i.e. one column, then it returns a vector rather than a data frame and if you want it to always return a data frame you would need instead:

df2[, n, drop = FALSE]

Upvotes: 1

Related Questions