Home > Enterprise >  R Error in `mutate()`: ! Problem while computing `Year = year(USER_Year)`. Caused by error in `as.PO
R Error in `mutate()`: ! Problem while computing `Year = year(USER_Year)`. Caused by error in `as.PO

Time:06-28

I know this question has been asked a lot of times but for some reason I still get this error even I though it should work based on the answers on this forum. Maybe I am missing a step.

Basically, I would like to change USER_Year from num to date so the leaflet map legend does not show the year with commas.

Sample Data (df):

structure(list(USER_Date = structure(c(18996, 18633, 19011, 19012, 
19016, 19019, 19020, 19011, 19023, 19023), class = "Date"), USER_Year = c(2022, 
2021, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022), USER_Month = c(1, 
1, 1, 1, 1, 1, 1, 1, 1, 1), USER_Day = c(4, 6, 19, 20, 24, 27, 
28, 19, 31, 31)), sfc_columns = c("x", "y"), class = "data.frame", row.names = c(NA, 
10L))

Code:

library(tidyverse)

# User lubridate
df = df %>%  mutate(Year = year(USER_Year))

Error:

Error in `mutate()`:
! Problem while computing `Year = year(USER_Year)`.
Caused by error in `as.POSIXlt.numeric()`:
! 'origin' must be supplied

CodePudding user response:

A date always has a year, month and day. So you will have to pick a random day like this:

df <- df %>%  
  mutate(Year = as.Date(paste(USER_Year, 1, 1, sep = "-")))

or better, use the actual month and day values:

df <- df %>%  
  mutate(Year = as.Date(paste(USER_Year, USER_Month, USER_Day, sep = "-")))

Then use format(df$Year, "%Y") to only get the year from the date

CodePudding user response:

I'd recommend converting the year to character instead. This should work with leaflet.

## Libraries
library(dplyr)
library(lubridate)

df$USER_Year1 = as.character(df$USER_Year)
str(df)

Output

> df$USER_Year1
 [1] "2022" "2021" "2022" "2022" "2022" "2022" "2022" "2022" "2022" "2022"
> df
    USER_Date USER_Year USER_Month USER_Day USER_Year1
1  2022-01-04      2022          1        4       2022
2  2021-01-06      2021          1        6       2021
3  2022-01-19      2022          1       19       2022
4  2022-01-20      2022          1       20       2022
5  2022-01-24      2022          1       24       2022
6  2022-01-27      2022          1       27       2022
7  2022-01-28      2022          1       28       2022
8  2022-01-19      2022          1       19       2022
9  2022-01-31      2022          1       31       2022
10 2022-01-31      2022          1       31       2022
> str(df)
'data.frame':   10 obs. of  5 variables:
 $ USER_Date : Date, format: "2022-01-04" "2021-01-06" "2022-01-19" "2022-01-20" ...
 $ USER_Year : num  2022 2021 2022 2022 2022 ...
 $ USER_Month: num  1 1 1 1 1 1 1 1 1 1
 $ USER_Day  : num  4 6 19 20 24 27 28 19 31 31
 $ USER_Year1: chr  "2022" "2021" "2022" "2022" ...
 - attr(*, "sfc_columns")= chr [1:2] "x" "y"
  • Related