I have a quite large database. I need to extract climate information from the "Nasapower" Library.
My reduced dataset looks like this:
api_decimal<- data.frame (
AP_COD = c("LOM_A", "LOM_L", "LOM_M", "LOM_LA", "LOM_CO"),
LAT_DEC = c(25.628,
25.641,
25.415,
25.435,
25.424),
LONG_DEC = c(7.300,
7.314,
7.450,
7.449,
7.443)
)
api_decimal$site <- paste(api_decimal$LAT_DEC, ",", api_decimal$LONG_DEC)
I tried to make a loop to extract the "daily" "Temperature (TM2)" information for the years 2014 to 2020 for all sites (latitude, longitude), but the loop doesn't work:
years <- c("2014", "2015", "2016", "2017", "2018", "2019")
for (i in seq_along(years)){
year <- years[[i]]
for(j in seq_along(nrow(api_decimal$site))) {
sites <- as.numeric(api_decimal$site[j, ])
ag_d <- get_power(
community = "ag",
lonlat = sites,
pars = "T2M",
dates = years,
temporal_api = "daily"
)
}
}
Any suggestions?
Thank in advance
There were a few problems with he code. First, since
nrow(api_decimal$site)isNULL,seq_along(nrow(api_decimal$site))evaluates tological(0). Instead, you wantseq_along(api_decimal$site). There were a couple of problems with your call toget_power(). First, thelonlatargument is meant to be a vector of length two. The way you're doing it in the code creates a single string with two decimals separated by a comma. When you turn this into a numeric value, it doesn't make two numeric values, it only makes a singleNAvalue. Instead, you can just use the longitude and latitude coordinates that are already in the data. Finally, thedatesargument wants length 2 character vector giving the start and end dates in YYYY-MM-DD format. You could make this by pasting your year variable to "-01-01" for the start and to "-12-31" for the end.If the loop had run, you would have also been overwriting
ag_dwith every iteration. You could solve that by initializingag_doutside the loop and then usingrbind(ag_d, new_result)to accumulate the results as you move through the iterations of the loop. This code should work: