In this tutorial, we will learn about data frames in R. We will cover the basics of creating, accessing, modifying, and performing operations on data frames.
A data frame in R is a table or two-dimensional array-like structure in which each column contains values of one variable and each row contains one set of values from each column. Data frames are used for storing data tables.
Data frames can be created in R using the data.frame()
function:
df <- data.frame(column1 = c(1, 2, 3), column2 = c('A', 'B', 'C'))
The above code creates a data frame with two columns, where column1
contains numeric values and column2
contains character values.
df
using the data.frame
function.id
with integer values, name
with character values, and age
with numeric values.df <- data.frame(id = c(1, 2, 3), name = c('Alice', 'Bob', 'Charlie'), age = c(25, 30, 35))
print(df)
id name age 1 1 Alice 25 2 2 Bob 30 3 3 Charlie 35
df
with columns id
, name
, and age
.name
column using the dollar sign $
operator and print it.[row, column]
notation and print it.df <- data.frame(id = c(1, 2, 3), name = c('Alice', 'Bob', 'Charlie'), age = c(25, 30, 35))
print(df$name)
print(df[1, 2])
[1] "Alice" "Bob" "Charlie" [1] "Alice"
df
with columns id
, name
, and age
.age
of the second row by assigning a new value to it.gender
to the data frame.df <- data.frame(id = c(1, 2, 3), name = c('Alice', 'Bob', 'Charlie'), age = c(25, 30, 35))
df$age[2] <- 32
df$gender <- c('F', 'M', 'M')
print(df)
id name age gender 1 1 Alice 25 F 2 2 Bob 32 M 3 3 Charlie 35 M
df
with columns id
, name
, and age
.age
is greater than 30.df_filtered
.df <- data.frame(id = c(1, 2, 3), name = c('Alice', 'Bob', 'Charlie'), age = c(25, 30, 35))
df_filtered <- df[df$age > 30, ]
print(df_filtered)
id name age 3 3 Charlie 35