Skip to content

Commit 2915c44

Browse files
committed
corrected coercion for dates and added tests
1 parent ac6fb82 commit 2915c44

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

R/utils.R

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@ coerce <- function(x, atomicclass) {
112112
"numeric" = as.numeric(x),
113113
"integer" = as.integer(x),
114114
"logical" = as.logical(x),
115-
"date" = as.POSIXct(as.integer(x))
115+
"date" = if (inherits(x, "POSIXct") || inherits(x, "Date")) {
116+
as.Date(x)
117+
} else {
118+
as.Date(as.integer(x), origin="1899-12-30")
119+
},
116120
)
117121
}

tests/testthat/test-utils.R

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,28 @@ test_that("function kvlist_to_table works", {
3838
guide <- list(otherstuff = list("a" = "A", "b" = "B"))
3939
expect_error(kvlist_to_table(kvlist, guide, reverse.translate = TRUE))
4040
})
41+
42+
test_that("function coerce works", {
43+
expect_equal(as.character(coerce(45748L, "date")), "2025-04-01")
44+
expect_equal(as.character(coerce(as.Date("2025-04-01"), "date")), "2025-04-01")
45+
expect_equal(coerce("45748", "integer"), 45748L)
46+
expect_equal(coerce("45748", "numeric"), 45748)
47+
expect_equal(coerce(45748L, "character"), "45748")
48+
expect_equal(coerce("true", "logical"), TRUE)
49+
})
50+
51+
test_that("Reading dates from an excel file yield correct dates", {
52+
excel_file <- test_path("testdata/dates_linux.xlsx")
53+
date1 <- readxl::read_excel(excel_file, sheet=1, range="A1:A2")
54+
date2 <- readxl::read_excel(excel_file, sheet=1, range="B1:B2")
55+
date3 <- readxl::read_excel(excel_file, sheet=1, range="C1:C2")
56+
expect_equal(coerce(date1 |> dplyr::pull(1), "date"), as.Date("1962-10-27"))
57+
expect_equal(coerce(date2 |> dplyr::pull(1), "date"), as.Date("1962-10-27"))
58+
expect_equal(coerce(date3 |> dplyr::pull(1), "date"), as.Date("1962-10-27"))
59+
date4 <- readxl::read_excel(excel_file, sheet=1, range="D1:D2")
60+
date5 <- readxl::read_excel(excel_file, sheet=1, range="E1:E2")
61+
date6 <- readxl::read_excel(excel_file, sheet=1, range="F1:F2")
62+
expect_equal(coerce(date4 |> dplyr::pull(1), "date"), as.Date("2025-04-01"))
63+
expect_equal(coerce(date5 |> dplyr::pull(1), "date"), as.Date("2025-04-01"))
64+
expect_equal(coerce(date6 |> dplyr::pull(1), "date"), as.Date("2025-04-01"))
65+
})
8.65 KB
Binary file not shown.

0 commit comments

Comments
 (0)