I know that to get a row from a data frame in R, we can do this:
data[row,] where row is an integer. But that spits out an ugly looking data structure where every column is labeled with the names of the column names. How can I just get it a row as a list of value?
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.
Data.frames created by importing data from a external source will have their data transformed to factors by default. If you do not want this set stringsAsFactors=FALSE
In this case to extract a row or a column as a vector you need to do something like this:
as.numeric(as.vector(DF[1,])) or like this
as.character(as.vector(DF[1,]))
You can't necessarily get it as a vector because each column might have a different mode. You might have numerics in one column and characters in the next.
If you know the mode of the whole row, or can convert to the same type, you can use the mode's conversion function (for example, as.numeric()) to convert to a vector. For example:
> state.x77[1,] Population Income Illiteracy Life Exp Murder HS Grad Frost 3615.00 3624.00 2.10 69.05 15.10 41.30 20.00 Area 50708.00 > as.numeric(state.x77[1,]) [1] 3615.00 3624.00 2.10 69.05 15.10 41.30 20.00 50708.00 This would work even if some of the columns were integers, although they would be converted to numeric floating-point numbers.
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