Q1. Using functions
## $Time
## [1] 1 2 3 4 5 7
##
## $demand
## [1] 8.3 10.3 19.0 16.0 15.6 19.8
Q2. Converting matrix into DataFrame
df1 <- data.frame(
Name = c("a", "b", "c", "d"),
Age = c(12, 34, 23, 67),
BMI = c(22, 12, 10, 11),
Country = c("Malaysia", "India", "Spain", "England")
)
head(df1, 6)## Name Age BMI Country
## 1 a 12 22 Malaysia
## 2 b 34 12 India
## 3 c 23 10 Spain
## 4 d 67 11 England
Q3. Accessing 1st & 2nd rows
df <- data.frame(
Name = c(
"Raju", "Kumar", "Chandru", "Deepak", "Raina",
"Dhoni", "Hema", "Vandana", "Bela", "Anand"
),
Age = c(12, 34, 23, 67, 23, 43, 23, 38, 34, 12),
Gender = c("M", "M", "M", "M", "M", "M", "F", "F", "F", "M"),
Country = c(
"Malaysia", "India", "Spain", "England", "Malaysia",
"Malaysia", "India", "Egypt", "Italy", "Peru"
)
)
first_two_rows <- df[1:2, ]
head(first_two_rows, 6)## Name Age Gender Country
## 1 Raju 12 M Malaysia
## 2 Kumar 34 M India
Q4. Accessing 1st & 2nd columns
## Name Age
## 1 Raju 12
## 2 Kumar 34
## 3 Chandru 23
## 4 Deepak 67
## 5 Raina 23
## 6 Dhoni 43
Q5. Sorting the dataframe
## Name Age Gender Country
## 1 Raju 12 M Malaysia
## 10 Anand 12 M Peru
## 3 Chandru 23 M Spain
## 5 Raina 23 M Malaysia
## 7 Hema 23 F India
## 2 Kumar 34 M India
Q6. Adding a new column
df_with_score <- df
df_with_score$Score <- c(85, 90, 78, 88, 90, 92, 80, 90, 87, 100)
head(df_with_score, 6)## Name Age Gender Country Score
## 1 Raju 12 M Malaysia 85
## 2 Kumar 34 M India 90
## 3 Chandru 23 M Spain 78
## 4 Deepak 67 M England 88
## 5 Raina 23 M Malaysia 90
## 6 Dhoni 43 M Malaysia 92
Q7. Filtering rows with a condition
## Name Age Gender Country
## 2 Kumar 34 M India
## 4 Deepak 67 M England
## 6 Dhoni 43 M Malaysia
## 8 Vandana 38 F Egypt
## 9 Bela 34 F Italy
Q8. Renaming columns
## Person Years Gender Nation
## 1 Raju 12 M Malaysia
## 2 Kumar 34 M India
## 3 Chandru 23 M Spain
## 4 Deepak 67 M England
## 5 Raina 23 M Malaysia
## 6 Dhoni 43 M Malaysia
Q9. Selecting multiple conditions
## Name Age BMI Country
## 2 b 34 12 India
## 3 c 23 10 Spain
## 4 d 67 11 England