library(dslabs)
data(murders)
murder_rate. Then use logical operators
to create a logical vector named low that tells us which
entries of murder_rate are lower than 1.# Calculate the murder rate per 100,000 for each state
murder_rate <- (murders$murder / murders$population) * 100000
# Create a logical vector for rates lower than 1
low <- murder_rate < 1
which to determine the indices of murder_rate
associated with values lower than 1.# Find the indices of rates lower than 1
indices_low <- which(low)
# Get the names of states with rates lower than 1
states_with_low_rates <- murders$state[indices_low]
low and the logical operator
&.# Define a logical vector for Northeast states
northeast <- murders$region == "Northeast"
# Find the states in the Northeast with rates lower than 1
northeast_low_rates <- murders$state[low & northeast]
# Compute the average murder rate for all states
average_murder_rate <- mean(murder_rate)
# Count the number of states with rates below the average
num_states_below_average <- sum(murder_rate < average_murder_rate)
murders$abb that match the three abbreviations, then use
the [ operator to extract the states.# Define a vector of abbreviations to match
abbreviations_to_match <- c("AK", "MI", "IA")
# Find the indices of the matching abbreviations
indices_match <- match(abbreviations_to_match, murders$abb)
# Extract the states using the indices
matching_states <- murders$state[indices_match]
# Define a vector of abbreviations to check
abbreviations_to_check <- c("MA", "ME", "MI", "MO", "MU")
# Create a logical vector to check if the abbreviations are in the dataset
actual_abbreviations <- abbreviations_to_check %in% murders$abb
# Use the ! operator to negate the logical vector
not_actual_abbreviation_index <- which(!actual_abbreviations)
# Find the non-abbreviation entry
non_abbreviation <- abbreviations_to_check[not_actual_abbreviation_index]