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
df$column_nameThe syntax to subset the column column_name data from the data frame df as a vector is
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
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 78Subset 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
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 78Conclusion
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.
