0

I was trying to use R to map with some data saved as 'csv' format. Date in my data is in YYYY-dd-mm format.I want to add some data information,like 'year''month',I used the following code:

 effort_df <- effort_df %>% 
  mutate(year  = year(date),
         month = month(date))

after running the code, I get the following error:

Error in as.POSIXlt.default(x, tz = tz(x)) : do not know how to convert 'x' to class “POSIXlt”

And the complete codes are as followings:

#Load packages
library(tidyverse) # for general data wrangling and plotting
library(furrr) # for parallel operations on lists
library(lubridate) # for working with dates
library(sf) # for vector data 
library(raster) # for working with rasters
library(maps) # additional helpful mapping packages
library(maptools)
library(rgeos)


# World polygons from the maps package
world_shp <- sf::st_as_sf(maps::map("world", plot = FALSE, fill = TRUE))
# Load EEZ polygons
eezs <- read_sf("F:/data/shapefiles/World_EEZ_v10_20180221", layer = 'eez_v10') %>% 
 filter(Pol_type == '200NM') # select the 200 nautical mile polygon layer
# Specify location of data directory containing daily csv files.  
data_dir <- ("F:/yjs/data/fishing_effort/fishing_effort")
# Create dataframe of filenames dates and filter to date range of interest
effort_files <- tibble(
 file = list.files(paste0(data_dir, 'fishing_effort_byflag'), 
                   pattern ='.csv', recursive = T, full.names = T),
 date =ymd(str_extract(file,
                        pattern = '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}')))
# Generate a vector of dates of interest using ymd from lubridate
effort_dates <- seq(ymd('2016-01-01'), ymd('2016-12-31'), by='days')

# Filter to files within our date range of interest
effort_files <- filter(effort_files, date %in% effort_dates)

# Read in data (uncomment to read in parallel)
plan(multisession)
effort_df <- furrr::future_map_dfr(effort_files$file, .f = read_csv)
class(effort_df$date)
# Add date information
effort_df <- effort_df %>% 
 mutate(year  = year(date),
        month = month(date))
# Specify new (lower) resolution in degrees for aggregating data
res <- 0.25
# Transform data across all fleets and geartypes
effort_df <- effort_df %>% 
 mutate(
   lat_bin = lat_bin / 100, 
   lon_bin = lon_bin / 100,
   lat_bin = floor(lat_bin/res) * res + 0.5 * res, 
   lon_bin = floor(lon_bin/res) * res + 0.5 * res)
# Re-aggregate the data to 0.25 degrees
effort_df <- effort_df %>% 
 group_by(date, year, month, lon_bin, lat_bin, flag, geartype) %>% 
 summarize(vessel_hours = sum(vessel_hours, na.rm = T),
           fishing_hours = sum(fishing_hours, na.rm = T),
           mmsi_present  = sum(mmsi_present, na.rm = T))
# Aggregate data across all fleets and geartypes
effort_all <- effort_df %>% 
 group_by(lon_bin,lat_bin) %>% 
 summarize(fishing_hours = sum(fishing_hours, na.rm = T),
           log_fishing_hours = log10(sum(fishing_hours, na.rm = T))) %>% 
 ungroup() %>% 
 mutate(log_fishing_hours = ifelse(log_fishing_hours <= 1, 1, log_fishing_hours),
        log_fishing_hours = ifelse(log_fishing_hours >= 5, 5, log_fishing_hours)) %>% 
 filter(fishing_hours >= 24)

# Linear green color palette function
effort_pal <- colorRampPalette(c('#0C276C', '#3B9088', '#EEFF00', '#ffffff'), 
                   interpolate = 'linear')
 # Map fishing effort
 p1 <- effort_all %>%
   ggplot() +
   geom_sf(data = world_shp, fill = '#374a6d', color = '#0A1738',size = 0.1) +
   geom_sf(data = eezs,color = '#374a6d',alpha = 0.2,fill = NA,size = 0.1) +
   geom_raster(aes(x=lon_bin,y=lat_bin,fill=log_fishing_hours)) +
   scale_fill_gradientn(
     "Fishing Hours",
     na.value = NA,limits <- c(1, 5),colours = effort_pal(5),
       labels <- c("10","100","1,000","10,000","100,000+"),values = scales::rescale(c(0, 1))) +
   labs(fill  = "Fishing hours (log scale)",
        title = "Global fishing effort in 2016") +
   guides(fill = guide_colourbar(barwidth = 10)) +
   gfw_theme

How can I solve this issue?

halfer
  • 19,824
  • 17
  • 99
  • 186
张玉磊
  • 1
  • 2
  • 2
    Can you add the result of `dput(head(effort_df))` to your question please. That way we can see your data and give better advice. – SymbolixAU Jul 18 '19 at 05:51
  • 张玉磊, please make this question *reproducible*. This includes sample code (including listing non-base R packages), sample *unambiguous* data (e.g., `dput(head(x))` or `data.frame(x=...,y=...)`), and expected output. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Jul 18 '19 at 05:51
  • `class(effort_df$date)` will tell you what type of data `date` is. Not just any number can be converted to a date using the `year` function. `?year` tells you which types of objects can be converted – Dij Jul 18 '19 at 05:59

1 Answers1

0
data_dir <- ("F:/yjs/data/fishing_effort/fishing_effort")

you lose / at the end of the path. The correct one should be

data_dir <- ("F:/yjs/data/fishing_effort/fishing_effort/")
lejlun
  • 4,140
  • 2
  • 15
  • 31
Cloe
  • 1