#Import and analyze UN FDI data dataun_latam_fdi_2023 <-here("Input", "graficos_tablas_cap1_mu.xlsx")# Specify the sheet and range and read the Excel file into a dataframeun_latam_fdi_2023_data <-read_excel(un_latam_fdi_2023, range ="Cuadro I.2!B9:H45")
New names:
• `` -> `...1`
# Rename the first column to "country"colnames(un_latam_fdi_2023_data)[1] <-"country"# Filter rows where country is either "Brazil" or "Total"filtered_data <- un_latam_fdi_2023_data %>%filter(country %in%c("Brazil", "Total"))# Convert all columns except 'country' to character typefiltered_data <- filtered_data %>%mutate(across(-country, as.character))# Reshape data to long formatlong_data <-pivot_longer(filtered_data, cols =-country, names_to ="Year", values_to ="Value")# Convert 'Value' from character to numericlong_data$Value <-as.numeric(long_data$Value)# Check if there were any conversion issuessum(is.na(long_data$Value))
[1] 0
# Convert 'Value' from millions to billionslong_data$Value <- long_data$Value /1000#plot the graphggplot(long_data, aes(x = Year, y = Value, group = country, color = country)) +geom_line() +geom_point() +# Adds points to the line for better visualizationtheme_minimal() +scale_x_discrete(name ="Year") +# Adjusted for categorical x-axisscale_y_continuous(name ="Value (Billions)",limits =c(0, NA), # Keep the lower limit at 0, automatically adjust upper limitexpand =expansion(add =c(0, 0))) +# Ensures Y-axis starts at 0labs(title ="Comparison of FDI Inflows Between Brazil and Total LATAM + Caribbean",x ="Year",y ="Value (Billions)",color ="Country") +scale_color_manual(values =c("Brazil"="blue", "Total"="red"))