Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using R convert data.frame to simple vector

Tags:

r

I have this data.frame:

> print(v.row)
    X1  X2  X3  X4  X5  X6  X7  X8  X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24
57 177 165 177 177 177 177 145 132 126 132 132 132 126 120 145 167 167 167 167 165 177 177 177 177
> dput(v.row)
structure(list(X1 = 177, X2 = 165, X3 = 177, X4 = 177, X5 = 177, 
    X6 = 177, X7 = 145, X8 = 132, X9 = 126, X10 = 132, X11 = 132, 
    X12 = 132, X13 = 126, X14 = 120, X15 = 145, X16 = 167, X17 = 167, 
    X18 = 167, X19 = 167, X20 = 165, X21 = 177, X22 = 177, X23 = 177, 
    X24 = 177), .Names = c("X1", "X2", "X3", "X4", "X5", "X6", 
"X7", "X8", "X9", "X10", "X11", "X12", "X13", "X14", "X15", "X16", 
"X17", "X18", "X19", "X20", "X21", "X22", "X23", "X24"), row.names = 57L, class = "data.frame")

I would remove all row and column names in order to get a simple vector. But the as.vector function doesn't work (it returns a data.frame).

> as.vector(v.row)
    X1  X2  X3  X4  X5  X6  X7  X8  X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24
57 177 165 177 177 177 177 145 132 126 132 132 132 126 120 145 167 167 167 167 165 177 177 177 177
like image 325
Alberto Avatar asked Feb 17 '13 19:02

Alberto


People also ask

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].

How do I turn a column into a numeric vector in R?

To convert a column to numeric in R, use the as. numeric() function. The as. numeric() is a built-in R function that returns a numeric value or converts any value to a numeric value.


2 Answers

see ?unlist

Given a list structure x, unlist simplifies it to produce a vector which contains all the atomic components which occur in x.

unlist(v.row)
[1] 177 165 177 177 177 177 145 132 126 132 132 132 126 120 145 167 167 167
       167 165 177 177 177 177

EDIT

You can do it with as.vector also, but you need to provide the correct mode:

 as.vector(v.row,mode='numeric')
 [1] 177 165 177 177 177 177 145 132 126 132 132 132 126 120 145 167 167
      167 167 165 177 177 177 177
like image 175
agstudy Avatar answered Sep 25 '22 17:09

agstudy


Just a note on the second part of agstudy's answer:

df <- data.frame(1:10) 
as.vector(df, mode="integer") #Error

as.vector(df[[1]],mode="integer") #Works; 
as.vector(df[[1]]) #Also works

i.e., apparently you have to select the list element from the dataframe even though there's only 1 element.

like image 36
John Avatar answered Sep 24 '22 17:09

John