Skip to content

Instantly share code, notes, and snippets.

@mdsumner
Last active December 9, 2022 16:27
Show Gist options
  • Save mdsumner/dbade9bb2a52bc53ce5413bf20c274e2 to your computer and use it in GitHub Desktop.
Save mdsumner/dbade9bb2a52bc53ce5413bf20c274e2 to your computer and use it in GitHub Desktop.

https://stackoverflow.com/questions/74705976/how-to-import-sinusoidal-remotesensed-data-into-raster-in-r

from Philippe Massicotte

f <- "~/ESACCI-OC-L3S-CHLOR_A-MERGED-1D_DAILY_4km_SIN_PML_OCx-20070101-fv5.0.nc"


library(tidync)
##
## the bins, this is every single bin for this sinusoidal grid
bins <- tidync::tidync(f) |> activate("D1") |>
 hyper_tibble()


## the bin is for joining on which bin_index is used here
d <- tidync::tidync(f) |> activate("D1,D0") |>
  hyper_tibble(select_var = c("chlor_a")) |> 
  dplyr::inner_join(bins, "bin_index")
  
d$time <- NULL

plot(d$lon, d$lat, pch = ".", col = palr::chl_pal(d$chlor_a))
  

image

Convert to terra (there's a lot of choices to be made here, I didn't look up the bin size resolution), but it depends how you want to summarize n:1 (if you do).

## define a raster
library(terra)
r <- terra::rast(terra::ext(c(-180, 180, -90, 90)), nrows = 900, ncols = 1800, crs = "OGC:CRS84")

cells <- tibble::tibble(cell = terra::cellFromXY(r, cbind(d$lon, d$lat)), chlor_a = d$chlor_a) |> 
 group_by(cell) |> summarize(chlor_a = mean(chlor_a))
r[cells$cell] <- cells$chlor_a
pal <- palr::chl_pal(palette = TRUE)
image(r, col = pal$cols[-1], breaks = pal$breaks)
@PMassicotte
Copy link

Quick question: how did you come up with nrows = 900 and ncols = 1800? 90' and 180'?

@mdsumner
Copy link
Author

mdsumner commented Dec 9, 2022

juat a guess! 4km L3 has a specific size, maybe 4320*2160 but I can't remember

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment