I have a dataframe such as:
a1 = c(1, 2, 3, 4, 5) a2 = c(6, 7, 8, 9, 10) a3 = c(11, 12, 13, 14, 15) aframe = data.frame(a1, a2, a3)
I tried the following to convert one of the columns to a vector, but it doesn't work:
avector <- as.vector(aframe['a2']) class(avector) [1] "data.frame"
This is the only solution I could come up with, but I'm assuming there has to be a better way to do this:
class(aframe['a2']) [1] "data.frame" avector = c() for(atmp in aframe['a2']) { avector <- atmp } class(avector) [1] "numeric"
Note: My vocabulary above may be off, so please correct me if so. I'm still learning the world of R. Additionally, any explanation of what's going on here is appreciated (i.e. relating to Python or some other language would help!)
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 extract a data frame column values as a vector by matching a vector in R, we can use subsetting with %in% operator.
Data Frames A data frame is a tabular data structure, consisting of rows and columns and implemented as a list. The columns of a data frame can consist of different data types but each column must be a single data type [like a vector].
I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.
A data frame is a list. When you subset a data frame using the name of a column and [
, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[
, or somewhat confusingly (to me) you could do aframe[,2]
which returns a vector, not a sublist.
So try running this sequence and maybe things will be clearer:
avector <- as.vector(aframe['a2']) class(avector) avector <- aframe[['a2']] class(avector) avector <- aframe[,2] class(avector)
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