library(dslabs)
data("murders")
pop <- murders$population
pop <- sort(pop)
smallest_population <- pop[1]
index_smallest_population <- order(murders$population)[1]
index_smallest_population <- which.min(murders$population)
states <- murders$state
state_with_smallest_population <- states[index_smallest_population]
temp<- c(35, 88, 42, 84, 81, 30)
city<- c(“Beijing”, “Lagos”, “Paris”, “Rio de Janeiro”, “San Juan”, “Toronto”)
city_temps<- data.frame(name = city, temperature = temp)
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.
ranks <- rank(murders$population)
my_df <- data.frame(state = states, rank = ranks)
ind <- order(ranks)
my_df <- my_df[ind, ]
data(“na_example”) str(na_example)
#> int [1:1000] 2 1 3 2 1 3 1 4 3 2 …
However, when we compute the average with the function mean, we obtain an NA: mean(na_example)
#> [1] NA
The is. na function returns a logical vector that tells us which entries are NA. Assign this logical vector ton object called ind and determine how many NAs na_example has.
data("na_example")
ind <- is.na(na_example)
number_of_nas <- sum(ind)
average_without_na <- mean(na_example[!ind])
temp <- c(35, 88, 42, 84, 81, 30)
city <- c(“Beijing”, “Lagos”, “Paris”, “Rio de Janeiro”, “San Juan”, “Toronto”)
city_temps <- data.frame(name = city, temperature = temp)
Remake the data frame using the code above, but add a line that converts the temperature from Fahrenheit to Celsius. The conversion is C = 5 9 × (F − 32).
temp <- c(35, 88, 42, 84, 81, 30)
city <- c("Beijing", "Lagos", "Paris", "Rio de Janeiro", "San Juan", "Toronto")
# Convert temperature from Fahrenheit to Celsius
temp_celsius <- (5/9) * (temp - 32)
city_temps <- data.frame(name = city, temperature = temp_celsius)
n <- 1000
sum_result <- 1
for (i in 2:n) {
sum_result <- sum_result + 1 / i^2
}
result <- sum_result
cat("The sum is approximately:", result)
## The sum is approximately: 1.643935
# Calculate the murder rate per 100,000 for each state
murder_rate <- (murders$total / murders$population) * 100000
# Compute the average murder rate for the US
us_average_murder_rate <- mean(murder_rate)
us_average_murder_rate
## [1] 2.779125