Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (7.3k points)

I want to create a vector out of a row of a data frame. But I don't want to have to row & column names. I tried several things... but had no luck.

This is my data frame:

> df <- data.frame(a=c(1,2,4,2),b=c(2,6,2,1),c=c(2.6,8.2,7.5,3))

> df

  a b   c

1 1 2 2.6

2 2 6 8.2

3 4 2 7.5

4 2 1 3.0

I tried:

> newV <- as.vector(df[1,])

> newV

  a b   c

1 1 2 2.6

But I really want something looking like that:

> newV <- c( 1,2,2.6)

> newV

[1] 1.0 2.0 2.6

Any help, much appreciated.

1 Answer

0 votes
by

To convert a row of a data frame to a vector, you can do the following:

 df <- data.frame(a=c(1,2,4,2),b=c(2,6,2,1),c=c(2.6,8.2,7.5,3))

> df

  a b   c

1 1 2 2.6

2 2 6 8.2

3 4 2 7.5

4 2 1 3.0

> as.numeric(df[1,])

[1] 1.0 2.0 2.6 #First row converted to a vector

You can also use the unlist function as follows:

unlist(df[1,])

  a   b   c 

1.0 2.0 2.6 #named vector

unname(unlist(df[1,]))

[1] 1.0 2.0 2.6 #unnamed vector

Browse Categories

...