Dolan Antenucci Dolan Antenucci - 1 year ago 101
R Question

R-friendly way to convert R 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'])
[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:

[1] "data.frame"
avector = c()
for(atmp in aframe['a2']) { avector <- atmp }
[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!)

Answer Source

I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.

A data frame is a list. When you subset a data frame using the name of a column and [, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[, or somewhat confusingly (to me) you could do aframe[,2] which returns a vector, not a sublist.

So try running this sequence and maybe things will be clearer:

avector <- as.vector(aframe['a2'])

avector <- aframe[['a2']]

avector <- aframe[,2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download