【问题标题】:Accessing all unknown columns in mutate function of r访问 r 的 mutate 函数中的所有未知列
【发布时间】:2019-09-30 18:13:28
【问题描述】:
  df <- tibble::tribble(  ~sev_curve, ~curve_type,  ~trend_date, ~weight,
                          "MILO",  'HOSPITALS',   '7/1/2020',      0.4,
                          'ALSO',  'PHYSICIANSC', '7/1/2020',      0.6)


df %>% mutate(new_column=#calls function on all columns of df)

所以以上大致就是我需要的。 df data.frame 可以有许多不同的列,下一行代码可能不知道。但它需要在所有这些列上调用一个函数来创建一个新列。

如何在 mutate 函数中访问 df 中的所有列?

【问题讨论】:

  • 您可以使用mutate_atmutate_all 哪些列是未知的? df %&gt;% mutate_all(list(new = ~ n_distinct(.)))
  • 你需要使用mutate吗?
  • @akrun sev_curve 和权重是已知的。其余的未知
  • @Mike 不,我不一定需要变异

标签: r dplyr


【解决方案1】:

我们可以使用mutate_at

library(dplyr)
df %>%
   mutate_at(vars(-one_of(c("sev_curve", "weight"))), list(new = ~ n_distinct(.)))
# A tibble: 2 x 6
#  sev_curve curve_type  trend_date weight curve_type_new trend_date_new
#  <chr>     <chr>       <chr>       <dbl>          <int>          <int>
#1 MILO      HOSPITALS   7/1/2020      0.4              2              1
#2 ALSO      PHYSICIANSC 7/1/2020      0.6              2              1

或者没有one_of

df %>%
   mutate_at(vars(-c("sev_curve", "weight")), list(new = ~ n_distinct(.)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多