'How to extract data from a region in netcdf file?

I've been trying to obtain chlorophyll values from an entire region with coordinates as shown below (lon and lat). So far, I've tried the following code, but get a couple errors:

library(raster) 
library(stringr)
library(lubridate)
library(tidyverse)
b <- brick('chl2020.nc')
lon = c(-2,120)
lat <- c(-30, 30)
points <- SpatialPoints(cbind(lon,lat))
points_data <- b %>%
raster::extract(points, df = T) %>%
gather(date, value, -ID) %>%
mutate(date = ymd(str_sub(names(b),2))) %>%
as_tibble()

And, I get the following error:

Error: Problem with mutate() column date. i date = ymd(str_sub(names(b), 2)). i date must be size 648 or 1, not 324. Run rlang::last_error() to see where the error occurred. In addition: Warning message: Problem with mutate() column date. i date = ymd(str_sub(names(b), 2)). i All formats failed to parse. No formats found.

Being a beginner in the interface, so I'm pretty sure I've missed a step somewhere in the code above. I would be grateful for some coding assistance in this.

My main aim is to get a table with monthly values of chlorophyll "chl" from Jan'20 to Dec'21.

(Dataset = https://drive.google.com/file/d/16B68a4j2EfwC0FoSiINg3-qmQTK97dCD/view?usp=sharing)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source