首页 > 解决方案 > 在 dplyr mutate 中返回多列

问题描述

mutate当函数返回多列时,如何将函数应用于列?下面我试图从一个字符列制作虚拟列(我知道制作虚拟列的方法可能有 100 多种,但这是为了说明返回多列的意义)。它返回美元符号(例如,Treatment$Isnonchilled而不是nonchilled如下图所示。这意味着该列不是原子向量而是数据框。

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)
    ) 

显示该列不是所需的原子向量,而是 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"

在此处输入图像描述

标签: rdplyr

解决方案


好吧,你不必修改你的函数。就这样做

CO2 %>%
  as_tibble() %>%
  mutate(
    conc2 = conc^2,
    across(c(Treatment), one_hot)$Treatment # see here
  ) 

输出

# A tibble: 84 x 7
   Plant Type   Treatment   conc uptake   conc2 Isnonchilled
   <ord> <fct>  <fct>      <dbl>  <dbl>   <dbl>        <int>
 1 Qn1   Quebec nonchilled    95   16      9025            1
 2 Qn1   Quebec nonchilled   175   30.4   30625            1
 3 Qn1   Quebec nonchilled   250   34.8   62500            1
 4 Qn1   Quebec nonchilled   350   37.2  122500            1
 5 Qn1   Quebec nonchilled   500   35.3  250000            1
 6 Qn1   Quebec nonchilled   675   39.2  455625            1
 7 Qn1   Quebec nonchilled  1000   39.7 1000000            1
 8 Qn2   Quebec nonchilled    95   13.6    9025            1
 9 Qn2   Quebec nonchilled   175   27.3   30625            1
10 Qn2   Quebec nonchilled   250   37.1   62500            1
# ... with 74 more rows

对于跨多个列的突变,

CO2 %>%
  as_tibble() %>%
  mutate(
    conc2 = conc^2,
    bind_cols(as.list(across(starts_with("T"), one_hot)))
  )

输出

# A tibble: 84 x 8
   Plant Type   Treatment   conc uptake   conc2 IsQuebec Isnonchilled
   <ord> <fct>  <fct>      <dbl>  <dbl>   <dbl>    <int>        <int>
 1 Qn1   Quebec nonchilled    95   16      9025        1            1
 2 Qn1   Quebec nonchilled   175   30.4   30625        1            1
 3 Qn1   Quebec nonchilled   250   34.8   62500        1            1
 4 Qn1   Quebec nonchilled   350   37.2  122500        1            1
 5 Qn1   Quebec nonchilled   500   35.3  250000        1            1
 6 Qn1   Quebec nonchilled   675   39.2  455625        1            1
 7 Qn1   Quebec nonchilled  1000   39.7 1000000        1            1
 8 Qn2   Quebec nonchilled    95   13.6    9025        1            1
 9 Qn2   Quebec nonchilled   175   27.3   30625        1            1
10 Qn2   Quebec nonchilled   250   37.1   62500        1            1
# ... with 74 more rows

推荐阅读