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
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?
CodePudding user response:
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"))