Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R Convert all values of multiple dataframe rows to one vector in order

I have a dataframe in R with observations that I would like to convert to one vector. All the rows have the same columns (with some NAs present in certain columns). I know that I can extract them all individually, but I am wondering what the most succinct way to extract all of the values (in order) is, to then convert them to one vector. I would like to read out all the values of row 1 (column-1, column-2… column-n), followed by row 2, followed by row 3…etc.

Example with sample data:

Row 1: 1, 2, 3, 4, 5, NA, 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Row 2: 2, 3, 4, 5, 6, 8, NA

Row 3: 7, 9, 2, 3, 5, 12, 14

Desired Vector: 1, 2, 3, 4, 5, NA, 1, 2, 3, 4, 5, 6, 8, NA, 7, 9, 2, 3, 5, 12, 14

To then remove NAs and receive:
1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 8, 7, 9, 2, 3, 5, 12, 14

Given that I have numerous rows and columns, what is the most succinct way to do this, rather than individually extracting each row/column’s values?

>Solution :

Try this

as.vector(na.omit(as.vector(t(as.matrix(df)))))
  • output
1  2  3  4  5  1  2  3  4  5  6  8  7  9  2  3  5 12 14
  • data
df <- structure(list(X1 = c(1, 2, 7), X2 = c(2, 3, 9), X3 = c(3, 4, 
2), X4 = c(4, 5, 3), X5 = c(5, 6, 5), X6 = c(NA, 8, 12), X7 = c(1, 
NA, 14)), class = "data.frame", row.names = c("x", "y", "z"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading