1

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

dpel
  • 1,696
  • 1
  • 19
  • 28

1 Answers1

5

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.

nicola
  • 23,063
  • 3
  • 31
  • 52