在 R 中调用非内置函数时遇到错误
Encountering an error while calling a non built-in function in R
我在 R 中创建了一个函数,它基本上根据指定的日期和 returns 它们的总和从我的数据框的列中获取某些值:
<<>>=
dmon.function = function(y, m, d){
result = sum(dmystatedf$Deceased[Dategood>="y-m-01" & Dategood<="y-m-d"])
}
dmon.function(2021, 04, 03)
@
现在当我传递这个函数时,我没有得到任何错误,但是当我调用这个函数时,我得到这个错误:
> dmon.function(2021, 04, 03)
Error in charToDate(x) :
character string is not in a standard unambiguous format
如何解决此错误?如何制作接受参数并将其用作日期、月份或年份的函数?
编辑 1: 以下是我使用的数据的前几行:
> 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
这是 Rui Barradas 在评论中要求的代码 dput(head(dmystatedf[c("Deceased", "Dategood")]))
的输出:
> 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")
谢谢
你不需要贡献包,仅基础 R 就足以解决问题。
基函数 ISOdate
接受 year
、month
和 day
和 returns class "POSIXt" "POSIXct"
的对象。然后与 class "Date"
列的比较将给出警告,因此使用 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
由 reprex package (v2.0.1)
于 2022-02-09 创建
我在 R 中创建了一个函数,它基本上根据指定的日期和 returns 它们的总和从我的数据框的列中获取某些值:
<<>>=
dmon.function = function(y, m, d){
result = sum(dmystatedf$Deceased[Dategood>="y-m-01" & Dategood<="y-m-d"])
}
dmon.function(2021, 04, 03)
@
现在当我传递这个函数时,我没有得到任何错误,但是当我调用这个函数时,我得到这个错误:
> dmon.function(2021, 04, 03)
Error in charToDate(x) :
character string is not in a standard unambiguous format
如何解决此错误?如何制作接受参数并将其用作日期、月份或年份的函数?
编辑 1: 以下是我使用的数据的前几行:
> 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
这是 Rui Barradas 在评论中要求的代码 dput(head(dmystatedf[c("Deceased", "Dategood")]))
的输出:
> 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")
谢谢
你不需要贡献包,仅基础 R 就足以解决问题。
基函数 ISOdate
接受 year
、month
和 day
和 returns class "POSIXt" "POSIXct"
的对象。然后与 class "Date"
列的比较将给出警告,因此使用 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
由 reprex package (v2.0.1)
于 2022-02-09 创建