How can I use mutate to apply a function to a column when the function returns multiple columns? Below I am trying to make dummy/one-hot columns from a character column (I know there are likely 100+ ways to make dummy columns but this is to illustrate the point of returning multiple columns). It returns the dollar signs (e.g., Treatment$Isnonchilled instead of just nonchilledas shown in the image below. This means the column is not an atomic vector but a data frame.
MWE
library(textshape)
library(dplyr)
one_hot <- function(x, drop.jth = TRUE, keep.na = TRUE, prefix = "Is", ...) {
y <- tibble::as_tibble(textshape::mtabulate(x))
if (keep.na) y[is.na(x), ] <- NA
if(drop.jth) y <- y[1:(ncol(y) - 1)]
colnames(y) <- paste0(prefix, colnames(y))
y
}
CO2 %>%
as_tibble() %>%
mutate(
conc2 = conc^2,
across(c(Treatment), one_hot)
)
Shows the column is not an atomic vector as desired but a data.frame
CO2 %>%
as_tibble() %>%
mutate(
conc2 = conc^2,
across(c(Treatment), one_hot)
) %>%
lapply(class)
$Plant
[1] "ordered" "factor"
$Type
[1] "factor"
$Treatment
[1] "tbl_df" "tbl" "data.frame"
$conc
[1] "numeric"
$uptake
[1] "numeric"
$conc2
[1] "numeric"
