R – Convert Data Frame Row to Vector

In this tutorial, we will learn how to convert a data frame row into a vector in R programming Language.

To get the data frame row as a vector in R, subset the row data using index.

The syntax to get the row with index i from data frame df as a vector is

</>
Copy
df[i,]

The above expression returns a data frame with a single row. We can convert this to a vector using as.numeric() [if all the values are numeric], or another appropriate function based on the type of data.

</>
Copy
as.numeric(df[i,])

Example

In this example, we take a data frame in df with five rows. We shall subset the row with index=3 data frame as a vector.

Example.R

</>
Copy
df = data.frame(x1 = c(10, 20, 30, 40, 50),
                x2 = c(44, 85, 23, 10, 78),
                x3 = c(0, 2, 4, 6, 8))

output = as.numeric(df[3,])
print(output)

Output

[1] 30 23  4

Conclusion

In this R Tutorial, we learned how to convert the row of a data frame to a vector, with the help of example programs.