Data Frames
- Data Frames are data displayed in a format as a table.
- Data Frames can have different types of data inside it. While the first column can be character, the second and third can be numeric or logical. However, each column should have the same type of data.
- Use the data.frame() function to create a data frame:
In [1]:
df <- data.frame (
Name = c("Karan", "Keisha", "Atharv"),
Age = c(30, 23, 27),
Marks = c(89, 97, 70)
)
In [2]:
df
Name | Age | Marks |
---|---|---|
<fct> | <dbl> | <dbl> |
Karan | 30 | 89 |
Keisha | 23 | 97 |
Atharv | 27 | 70 |
In [3]:
summary(df)
Name Age Marks Atharv:1 Min. :23.00 Min. :70.00 Karan :1 1st Qu.:25.00 1st Qu.:79.50 Keisha:1 Median :27.00 Median :89.00 Mean :26.67 Mean :85.33 3rd Qu.:28.50 3rd Qu.:93.00 Max. :30.00 Max. :97.00
In [4]:
df[1]
Name |
---|
<fct> |
Karan |
Keisha |
Atharv |
In [5]:
df[["Name"]]
- Karan
- Keisha
- Atharv
Levels:
- ‘Atharv’
- ‘Karan’
- ‘Keisha’
In [6]:
df$Name
- Karan
- Keisha
- Atharv
Levels:
- ‘Atharv’
- ‘Karan’
- ‘Keisha’
In [7]:
df$Name <- as.character(df$Name)
In [8]:
new_row <- c("Priya", 88, 99)
df1 <- rbind(df, new_row)
df1
Name | Age | Marks |
---|---|---|
<chr> | <chr> | <chr> |
Karan | 30 | 89 |
Keisha | 23 | 97 |
Atharv | 27 | 70 |
Priya | 88 | 99 |
In [9]:
df2 <- cbind(df, Roll_No = c(10, 11, 12))
df2
Name | Age | Marks | Roll_No |
---|---|---|---|
<chr> | <dbl> | <dbl> | <dbl> |
Karan | 30 | 89 | 10 |
Keisha | 23 | 97 | 11 |
Atharv | 27 | 70 | 12 |
In [10]:
df3 <- df[-c(1), -c(1)]
df3
Age | Marks | |
---|---|---|
<dbl> | <dbl> | |
2 | 23 | 97 |
3 | 27 | 70 |
In [11]:
dim(df)
- 3
- 3
In [12]:
ncol(df)
3
In [13]:
nrow(df)
3
In [14]:
length(df)
3
In [15]:
df1 <- data.frame (
Name = c("Karan", "Keisha", "Atharv"),
Age = c(30, 23, 27),
Marks = c(89, 97, 70)
)
df2 <- data.frame (
Name = c("Akshay", "Robin", "Manish"),
Age = c(31, 24, 28),
Marks = c(69, 91, 77)
)
df <- rbind(df1, df2)
df
Name | Age | Marks |
---|---|---|
<fct> | <dbl> | <dbl> |
Karan | 30 | 89 |
Keisha | 23 | 97 |
Atharv | 27 | 70 |
Akshay | 31 | 69 |
Robin | 24 | 91 |
Manish | 28 | 77 |
In [16]:
df <- cbind(df1, df2)
df
Name | Age | Marks | Name | Age | Marks |
---|---|---|---|---|---|
<fct> | <dbl> | <dbl> | <fct> | <dbl> | <dbl> |
Karan | 30 | 89 | Akshay | 31 | 69 |
Keisha | 23 | 97 | Robin | 24 | 91 |
Atharv | 27 | 70 | Manish | 28 | 77 |