0 votes
1 view
in R Programming by (5.2k points)

I have a data frame 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"

1 Answer

0 votes
by (25.3k points)

To convert a data frame column to a vector, you can use the following:


Using the [[ ]] (double square brackets) to extract the atomic values from the data frame.

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)

avector <- aframe[['a2']]

 avector

[1]  6 7 8  9 10

 class(avector)

[1] "numeric"

Using the following syntax:

avector <- aframe[,2]

avector

[1]  6 7 8  9 10

 

class(avector)

[1] "numeric"

 

Using the pull function from the dplyr package.

pull(aframe, a2)

[1]  6 7 8  9 10 

class(pull(aframe, a2))

[1] "numeric"

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...