Create new dataframe r
Here are a few ways to create a new dataframe in R:
Method 1: Using the data.frame()
function
df <- data.frame(column1 = c(1, 2, 3), column2 = c("a", "b", "c"))
This creates a dataframe with two columns, column1
and column2
, and three rows.
Method 2: Using the data.frame()
function with named vectors
v1 <- c(1, 2, 3)
v2 <- c("a", "b", "c")
df <- data.frame(v1, v2)
This creates a dataframe with two columns, v1
and v2
, and three rows.
Method 3: Using the tibble()
function from the tibble
package
library(tibble)
df <- tibble(column1 = c(1, 2, 3), column2 = c("a", "b", "c"))
This creates a dataframe with two columns, column1
and column2
, and three rows.
Method 4: Using the as.data.frame()
function
x <- matrix(c(1, 2, 3, "a", "b", "c"), nrow = 3)
df <- as.data.frame(x)
This creates a dataframe from a matrix.
You can also create a dataframe from a list of vectors using the data.frame()
function:
list1 <- list(v1 = c(1, 2, 3), v2 = c("a", "b", "c"))
df <- data.frame(list1)
This creates a dataframe with two columns, v1
and v2
, and three rows.
These are just a few examples of how you can create a new dataframe in R. The data.frame()
function is a powerful tool that allows you to create dataframes from various types of data, including vectors, matrices, and lists.