I made a function in R which basically takes certain values from a column of my dataframe according to the dates specified and returns their sum:
<<>>=
dmon.function = function(y, m, d){
result = sum(dmystatedf$Deceased[Dategood>="y-m-01" & Dategood<="y-m-d"])
}
dmon.function(2021, 04, 03)
@
Now when I pass the function, I get no error, but when I call the function, I get this error:
> dmon.function(2021, 04, 03)
Error in charToDate(x) :
character string is not in a standard unambiguous format
How do I resolve this error? How to I make functions that takes arguments and use them as dates, months, or years in general?
EDIT 1: Here are the first few rows of the data I'm using:
> head(dmystatedf[c("Deceased", "Dategood")])
Deceased Dategood
61 0 2020-03-09
74 0 2020-03-10
87 0 2020-03-11
101 0 2020-03-12
115 1 2020-03-13
130 1 2020-03-14
Here is the output of the code dput(head(dmystatedf[c("Deceased", "Dategood")]))
as requested by Rui Barradas in comments:
> dput(head(dmystatedf[c("Deceased", "Dategood")]))
structure(list(Deceased = c(0L, 0L, 0L, 0L, 1L, 1L), Dategood = structure(18330:18335, class = "Date")), row.names = c(61L,
74L, 87L, 101L, 115L, 130L), class = "data.frame")
THANK YOU
CodePudding user response:
You don't need contributed packages, base R alone is enough to solve the question's problem.
Base function ISOdate
accepts year
, month
and day
and returns an oject of class "POSIXt" "POSIXct"
. Then the comparisons to the column of class "Date"
will give warnings so coerce the start and end dates with as.Date
.
dmon.function <- function(y, m, d){
start <- as.Date(ISOdate(y, m, 1))
end <- as.Date(ISOdate(y, m, d))
sum(dmystatedf$Deceased[dmystatedf$Dategood >= start & dmystatedf$Dategood <= end])
}
dmon.function(2021, 04, 03)
#> [1] 0
Created on 2022-02-09 by the reprex package (v2.0.1)