Using PVWatt's API tool, I am trying to create a code in R that will read a list of rows (located within dataset "test.csv") each containing a specific latitude and longitude coordinate. I would like for the code to return annual kWh values for each row. I tried with the following code but the new columns "AnnualEnergy" and "CapacityFactor" contain NA values:
library(httr)
library(jsonlite)
# Read data from CSV file
data <- read.csv("test.csv")
# Function to send request to PVWatts API for a single location
pvwatts_request <- function(latitude, longitude) {
url <- "https://developer.nrel.gov/api/pvwatts/v8.json"
parameters <- list(
api_key = "XXX",
lat = Latitude,
lon = Longitude,
system_capacity = 4, # Example system capacity (kW)
module_type = 0, # 0: Standard, 1: Premium, 2: Thin film
losses = 14, # System losses (percent)
azimuth = 180, # Azimuth angle (degrees)
tilt = 20, # Tilt angle (degrees)
array_type = 1, # 0: Fixed, 1: Tracking
module_parameters = toJSON(list(
"module_efficiency" = 0.16 # Example module efficiency
))
)
response <- GET(url, query = parameters)
content(response, "parsed")
}
# Create empty columns for PVWatts API results
data$AnnualEnergy <- NA
data$CapacityFactor <- NA
# Add more columns as needed
# Iterate over rows, send requests, and store results
for (i in 1:nrow(data)) {
latitude <- data[i, "Latitude"]
longitude <- data[i, "Longitude"]
result <- tryCatch(pvwatts_request(latitude, longitude), error = function(e) NULL)
if (!is.null(result) && !is.null(result$outputs)) {
data[i, "AnnualEnergy"] <- result$outputs$ac_annual
data[i, "CapacityFactor"] <- result$outputs$capacity_factor
# Add more columns as needed
} else {
cat("Error occurred or empty response for row", i, "\n")
cat("Latitude:", latitude, "Longitude:", longitude, "\n")
print(result) # Print out the API response for inspection
}
}
# Save updated data to a new CSV file
write.csv(data, "data_with_results2.csv", row.names = FALSE)
I asked ChatGTP 3.5 to develop the code, and that is what it came up with. I was expecting to return annual kWh values for each entry.