Here's the corrected R code that properly handles the table structure from the source website:
text
library(rvest)
library(dplyr)
library(tidyr)
url <-
webpage <- read_html(url)
Extract all climate tables (4 tables total: 2 for high temps, 2 for low temps)
all_tables <- webpage %>%
html_nodes("table") %>%
html_table(header = TRUE)
Function to process temperature tables
process_temp_tables <- function(first_table, second_table) {
bind_rows(
all_tables[[first_table]] %>% select(Month = 1, Value = 2),
all_tables[[second_table]] %>% select(Month = 1, Value = 2)
) %>%
mutate(Value = as.numeric(gsub("[^0-9.]", "", Value)))
}
Process high temperatures (Tables 1 and 2)
high_temp <- process_temp_tables(1, 2) %>% rename(High = Value)
Process low temperatures (Tables 3 and 4)
low_temp <- process_temp_tables(3, 4) %>% rename(Low = Value)
Combine and format final dataset
climate_data <- high_temp %>%
left_join(low_temp, by = "Month") %>%
mutate(Month = factor(Month, levels = month.name)) %>%
arrange(Month) %>%
select(Month, High, Low)
Display final organized data
print(climate_data)
Key Fixes and Features:
Explicit Table Handling:
First 2 tables contain high temps (Jan-Jun and Jul-Dec)
Next 2 tables contain low temps (Jan-Jun and Jul-Dec)
Uses separate processing for each temperature type
Data Validation:
text
Verify table counts
stopifnot(length(all_tables) >= 4)
Check temperature relationships
stopifnot(all(climate_dataHigh>climatedataLow, na.rm = TRUE))
Expected Output Structure:
text
Month High Low
1 January 50 28
2 February 54 29
3 March 63 37
4 April 72 46
5 May 79 56
6 June 85 65
7 July 89 70
8 August 87 68
9 September 81 60
10 October 72 47
11 November 63 37
12 December 54 30
Error Prevention:
Explicit numeric conversion with character cleaning
Factor-based month ordering
Table index validation
If you need precipitation data from additional tables, you can extend this pattern:
text
For precipitation (Tables 5 and 6):
precip <- process_temp_tables(5, 6) %>% rename(Precipitation = Value)
climate_data <- climate_data %>% left_join(precip, by = "Month")
Note: Table indices may require adjustment if the website updates its layout. Always verify the actual table structure using browser developer tools before running the scraper.
Share
Export