Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!)

like image 816
Dolan Antenucci Avatar asked Aug 15 '11 20:08

Dolan Antenucci


People also ask

How do you convert a row of a Dataframe to a vector in R?

If we want to turn a dataframe row into a character vector then we can use as. character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.

How do I extract a vector from a Dataframe in R?

To extract a data frame column values as a vector by matching a vector in R, we can use subsetting with %in% operator.

Is a Dataframe a vector?

Data Frames A data frame is a tabular data structure, consisting of rows and columns and implemented as a list. The columns of a data frame can consist of different data types but each column must be a single data type [like a vector].


1 Answers

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']) class(avector)   avector <- aframe[['a2']] class(avector)  avector <- aframe[,2] class(avector) 
like image 192
joran Avatar answered Oct 06 '22 10:10

joran