【问题标题】:warning message with mutate_at() in dplyr packagedplyr 包中带有 mutate_at() 的警告消息
【发布时间】:2020-02-15 05:24:36
【问题描述】:

dplyr 包中使用mutate_at() 时收到一条警告消息。

dt %>% 
  mutate_at(
    c(5:43),
    funs(pc = ./Population)
    )
Warning message:
funs() is soft deprecated as of dplyr 0.8.0
Please use a list of either functions or lambdas: 

  # Simple named list: 
  list(mean = mean, median = median)

  # Auto named with `tibble::lst()`: 
  tibble::lst(mean, median)

  # Using lambdas
  list(~ mean(., trim = .2), ~ median(., na.rm = TRUE))
This warning is displayed once per session. 

还有其他功能吗?
如何使用data.table 传递它。

【问题讨论】:

    标签: r dplyr data.table data-manipulation


    【解决方案1】:

    使用最新版本的dplyr,它将是list

    library(dplyr)
    dt %>% 
      mutate_at(5:43,
             list(pc = ~ ./Population))
    

    可重现的例子

    head(mtcars) %>%
           mutate_at(4:5, list(pc = ~ ./wt))
    #    mpg cyl disp  hp drat    wt  qsec vs am gear carb    hp_pc   drat_pc
    #1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 41.98473 1.4885496
    #2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 38.26087 1.3565217
    #3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 40.08621 1.6594828
    #4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 34.21462 0.9580093
    #5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 50.87209 0.9156977
    #6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 30.34682 0.7976879
    

    警告信息是友好的警告,无需担心


    data.table 中,我们在.SDcols 中指定它

    library(data.table)
    setDT(dt)[, paste0(names(dt)[5:43], "_pc") := 
               lapply(.SD, function(x) x/Population), .SDcols = 5:43]
    

    或使用base R

    nm1 <- names(dt)[5:43]
    dt[paste0(nm1, "_pc")] <- lapply(dt[nm1], `/`, dt[["Population"]])
    

    或者直接

    dt[paste0(nm1, "_pc")] <- dt[nm1]/dt[["Population"]]
    

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 2016-07-05
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多