Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (7.3k points)
edited by

I have a data frame with numeric entries like this one

test <- data.frame(x = c(26, 21, 20), y = c(34, 29, 28))

How can I get the following vector?

> 26, 34, 21, 29, 20, 28

I was able to get it using the following, but I guess there should be a much more elegant way

X <- test[1, ]

for (i in 2:dim(test)[ 1 ]){

   X <- cbind(X, test[i, ])

   }

1 Answer

+1 vote
by
edited by

To convert the rows of a data frame to a vector, you can use the as.vector function with transpose of the data frame.i.e,

test <- data.frame(x = c(26, 21, 20), y = c(34, 29, 28))

as.vector(t(test))

[1] 26 34 21 29 20 28

To convert the columns:

unlist(test)

x1 x2 x3 y1 y2 y3 

26 21 20 34 29 28 

If you want to learn more about R programming watch this tutorial on Introduction to Data Science with R

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...