Skip to content

Commit ae88794

Browse files
authored
Merge pull request #697 from DavisVaughan/vec-cast-list
`vec_cast.list.*()` improvements
2 parents 851b568 + b25174d commit ae88794

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

R/type-bare.R

+10-1
Original file line numberDiff line numberDiff line change
@@ -413,12 +413,14 @@ vec_cast.list.list <- function(x, to, ...) {
413413
#' @export
414414
#' @method vec_cast.list default
415415
vec_cast.list.default <- function(x, to, ...) {
416-
if (inherits(x, "vctrs_unspecified")) {
416+
if (is_unspecified(x)) {
417417
return(vec_init(to, length(x)))
418418
}
419419

420420
out <- lapply(seq_along(x), function(i) x[[i]])
421421

422+
vec_slice(out, vec_equal_na(x)) <- list(NULL)
423+
422424
if (!is.object(to)) {
423425
out <- shape_broadcast(out, to)
424426
}
@@ -433,6 +435,13 @@ vec_cast.list.data.frame <- function(x, to, ...) {
433435
# equivalent for `vec_get()`
434436
row.names(x) <- NULL
435437
out <- vec_chop(x)
438+
439+
vec_slice(out, vec_equal_na(x)) <- list(NULL)
440+
441+
if (!is.object(to)) {
442+
out <- shape_broadcast(out, to)
443+
}
444+
436445
out
437446
}
438447

tests/testthat/test-type-bare.R

+23-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ test_that("can sort raw", {
302302

303303
test_that("safe casts work as expected", {
304304
expect_equal(vec_cast(NULL, list()), NULL)
305-
expect_equal(vec_cast(NA, list()), list(NA))
305+
expect_equal(vec_cast(NA, list()), list(NULL))
306306
expect_equal(vec_cast(1:2, list()), list(1L, 2L))
307307
expect_equal(vec_cast(list(1L, 2L), list()), list(1L, 2L))
308308
})
@@ -320,6 +320,28 @@ test_that("data frames are cast to list row wise (#639)", {
320320
expect_equal(vec_cast(x, list()), expect)
321321
})
322322

323+
test_that("data frames can be cast to shaped lists", {
324+
to <- array(list(), dim = c(0, 2, 1))
325+
x <- data.frame(x = 1:2, y = 3:4)
326+
327+
expect <- list(vec_slice(x, 1), vec_slice(x, 2))
328+
expect <- array(expect, dim = c(2, 2, 1))
329+
330+
expect_equal(vec_cast(x, to), expect)
331+
})
332+
333+
test_that("Casting atomic `NA` values to list results in a `NULL`", {
334+
x <- c(NA, 1)
335+
expect <- list(NULL, 1)
336+
expect_equal(vec_cast(x, list()), expect)
337+
})
338+
339+
test_that("Casting data frame `NA` rows to list results in a `NULL`", {
340+
x <- data.frame(x = c(NA, NA, 1), y = c(NA, 1, 2))
341+
expect <- list(NULL, vec_slice(x, 2), vec_slice(x, 3))
342+
expect_equal(vec_cast(x, list()), expect)
343+
})
344+
323345
# Unspecified
324346

325347
test_that("unspecified can be cast to bare methods", {

0 commit comments

Comments
 (0)