In R, a data frame is a two-dimensional table-like structure, where each column can have a different data type. Data frames are a common way of representing data in R, especially for statistical analysis.
To create a data frame in R, you can use the data.frame() function. This function takes named arguments, where the names are the column names and the values are vectors containing the data for each column. Here’s an example:
# Creating a data frame
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
height = c(1.6, 1.8, 1.7),
married = c(TRUE, TRUE, FALSE)
)
# Displaying the data frame
df
In this example, we’ve created a data frame with four columns: "name", "age", "height", and "married". The "name" column contains character strings, the "age" column contains numeric values, the "height" column contains numeric values with decimal places, and the "married" column contains logical values (TRUE or FALSE).
You can also add a new column to an existing data frame by assigning a vector to a new column name. For example, to add a "weight" column to the df data frame, you can write:
df$weight <- c(60, 80, 70)
This creates a new column named "weight" and assigns it the vector c(60, 80, 70).
Once you’ve created a data frame, you can perform operations on it using built-in functions like summary(), which provides a summary of the columns, or subset(), which creates a subset of the data frame based on specified criteria.
In summary, a data frame is a two-dimensional table-like structure in R that can contain columns of different data types. You can create a data frame using the data.frame() function, and you can add new columns using indexing with the $ operator.