Convert data.frame column to a vector?

I have a dataframe such as:

a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)

I tried the following to convert one of the columns to a vector, but it doesn’t work:

avector <- as.vector(aframe['a2'])
class(avector) 
[1] "data.frame"

This is the only solution I could come up with, but I’m assuming there has to be a better way to do this:

class(aframe['a2']) 
[1] "data.frame"
avector = c()
for(atmp in aframe['a2']) { avector <- atmp }
class(avector)
[1] "numeric"

Note: My vocabulary above may be off, so please correct me if so. I’m still learning the world of R. Additionally, any explanation of what’s going on here is appreciated (i.e. relating to Python or some other language would help!)

11 Answers
11

Leave a Comment