I have a dataframe 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, ]) }
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.
To create a vector of data frame values by rows we can use c function after transposing the data frame with t. For example, if we have a data frame df that contains many columns then the df values can be transformed into a vector by using c(t(df)), this will print the values of the data frame row by row.
Rotating or transposing R objects frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command. The result of the t() command is always a matrix object.
You can try as.vector(t(test))
. Please note that, if you want to do it by columns you should use unlist(test)
.
c(df$x, df$y) # returns: 26 21 20 34 29 28
if the particular order is important then:
M = as.matrix(df) c(m[1,], c[2,], c[3,]) # returns 26 34 21 29 20 28
Or more generally:
m = as.matrix(df) q = c() for (i in seq(1:nrow(m))){ q = c(q, m[i,]) } # returns 26 34 21 29 20 28
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With