Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a row from a data frame as a vector in R

Tags:

r

I know that to get a row from a data frame in R, we can do this:

data[row,]  

where row is an integer. But that spits out an ugly looking data structure where every column is labeled with the names of the column names. How can I just get it a row as a list of value?

like image 430
StanLe Avatar asked Sep 30 '11 19:09

StanLe


People also ask

How do I convert a DataFrame row 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.


2 Answers

Data.frames created by importing data from a external source will have their data transformed to factors by default. If you do not want this set stringsAsFactors=FALSE

In this case to extract a row or a column as a vector you need to do something like this:

as.numeric(as.vector(DF[1,])) 

or like this

as.character(as.vector(DF[1,])) 
like image 68
David R. Avatar answered Sep 23 '22 04:09

David R.


You can't necessarily get it as a vector because each column might have a different mode. You might have numerics in one column and characters in the next.

If you know the mode of the whole row, or can convert to the same type, you can use the mode's conversion function (for example, as.numeric()) to convert to a vector. For example:

> state.x77[1,] Population     Income Illiteracy   Life Exp     Murder    HS Grad      Frost     3615.00    3624.00       2.10      69.05      15.10      41.30      20.00        Area    50708.00  > as.numeric(state.x77[1,]) [1]  3615.00  3624.00     2.10    69.05    15.10    41.30    20.00 50708.00 

This would work even if some of the columns were integers, although they would be converted to numeric floating-point numbers.

like image 28
Michael Hoffman Avatar answered Sep 26 '22 04:09

Michael Hoffman