R – Convert Data Frame Column to Vector

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

To get the data frame column as a vector in R, extract the column from data frame using $ notation or subset the column data. In both the cases, the column is returned as a vector.

The syntax to get the column column_name from data frame df as a vector using $ notation is

</>
Copy
df$column_name

The syntax to subset the column column_name data from the data frame df as a vector is

</>
Copy
df[,"column_name"]

Examples

Extract Column from Data Frame using $ Notation

In this example, we take a data frame in df with columns x1, x2, and x3. We shall extract the column x2 from the data frame as a vector.

Example.R

</>
Copy
df = data.frame(x1 = c("A", "B", "C", "D", "E"),
                x2 = c(44, 85, 23, 10, 78),
                x3 = c(0, 2, 4, 6, 8))

output = df$x2
print(output)

Output

[1] 44 85 23 10 78

Subset Column from Data Frame as Vector

In this example, we take a data frame in df with columns x1, x2, and x3. We shall subset the column x2 from the data frame as a vector.

Example.R

</>
Copy
df = data.frame(x1 = c("A", "B", "C", "D", "E"),
                x2 = c(44, 85, 23, 10, 78),
                x3 = c(0, 2, 4, 6, 8))

output = df[,"x2"]
print(output)

Output

[1] 44 85 23 10 78

Conclusion

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