Skip to content

Commit

Permalink
Merge pull request #791 from markfairbanks/pivot_wider-only-used-cols
Browse files Browse the repository at this point in the history
`pivot_wider()`: Only use used cols
  • Loading branch information
markfairbanks authored Dec 21, 2023
2 parents 37bfdbc + 8780351 commit cdf3533
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
13 changes: 7 additions & 6 deletions R/pivot_wider.R
Original file line number Diff line number Diff line change
Expand Up @@ -128,18 +128,18 @@ pivot_wider.tidytable <- function(.df,

formula <- glue("{lhs} ~ {rhs}")

dcast_call <- call2(
.dcast_df <- select(.df, any_of(c(id_cols, names_from, values_from)))

out <- eval_tidy(call2(
"dcast",
quo(.df),
quo(.dcast_df),
formula = formula,
value.var = values_from,
fun.aggregate = expr(!!values_fn),
sep = names_sep,
fill = values_fill,
.ns = "data.table"
)

out <- eval_tidy(dcast_call)
))

out <- remove_key(out)

Expand All @@ -163,7 +163,8 @@ pivot_wider.tidytable <- function(.df,
.by = any_of(id_cols))
out <- left_join(out, unused_df, by = id_cols)
}
out

as_tidytable(out)
}

#' @export
Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/test-pivot_wider.R
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,25 @@ test_that("correctly labels columns when `names_glue` is used, #579", {

# unused -------------------------------------------------------------------

test_that("only uses used columns when `unused_fn = NULL`, #698", {
df <- data.frame(
a = LETTERS[1:2],
b = LETTERS[3:4],
val = 1:2
)

res <- df %>%
pivot_wider(
id_cols = character(0),
names_from = a,
values_from = val
)

expect_named(res, c("A", "B"))
expect_equal(res$A, 1)
expect_equal(res$B, 2)
})

test_that("`unused_fn` can summarize unused columns (#990)", {
df <- tidytable(
id = c(1, 1, 2, 2),
Expand Down

0 comments on commit cdf3533

Please sign in to comment.