dpel
dpel

Reputation: 2123

Create a matrix based on names

I would like to create a matrix using characters. The characters are names of vectors in a data frame.

df <- data.frame(rnorm(100),rnorm(100),rnorm(100),rnorm(100))
colnames(df) <- c("a1","b1","c1","d1")
a <- paste("df$",names(df), sep = "")

How can I use these characters to reference the data frame and take the data in the vector to a matrix? Something like:

as.matrix(cbind(df$a1,df$b1))

but instead of me writing df$a1,df$b1 these names come from a

Upvotes: 1

Views: 192

Answers (1)

nicola
nicola

Reputation: 24480

Just use

as.matrix(df[,vec]) 

where vec is either a numeric vector whose values are the column indices you want to keep or a character vector with the names of the columns.

Upvotes: 5

Related Questions