2: Now instead of the smallest population size, fnd the index of the
entry with the smallest population size. Hint: use order instead of
sort.
population_data <- data.frame(
country = c("Country A", "Country B", "Country C", "Country D"),
population = c(1000000, 500000, 200000, 3000000)
)
pop <- population_data$population
index_of_smallest <- order(pop)[1]
index_of_smallest
## [1] 3
5: Use the rank function to determine the population rank of each
state from smallest population size to biggest. Save these ranks in an
object called ranks, then create a data frame with the state name and
its rank. Call the data frame my_df
murders <- data.frame(
state = c("State A", "State B", "State C", "State D"),
population = c(1000000, 500000, 2000000, 300000)
)
ranks <- rank(murders$population)
my_df <- data.frame(state = murders$state, rank = ranks)
my_df
## state rank
## 1 State A 3
## 2 State B 2
## 3 State C 4
## 4 State D 1
6 : Repeat the previous exercise, but this time order my_df so that
the states are ordered from least populous to most populous. Hint:
create an object ind that stores the indexes needed to order the
population values. Then use the bracket operator [ to re-order each
column in the data frame
ranks <- rank(murders$population)
my_df <- data.frame(state = murders$state, rank = ranks)
ind <- order(murders$population)
my_df <- my_df[ind, ]
my_df
## state rank
## 4 State D 1
## 2 State B 2
## 1 State A 3
## 3 State C 4