【问题标题】:R - own function in mutate_if from dplyrR - 来自 dplyr 的 mutate_if 中的自己的函数
【发布时间】:2019-04-24 18:18:37
【问题描述】:

为了使用 dplyr 中的函数mutate_if(),我只能通过定义上游的函数找到一种方法,如下所示:

library(dplyr)    
data(iris)

f1 <- function(x){ max(x) < 1 }
f2 <- function(x){ x / max(x) }

df <- iris %>%
   mutate_if(f1, f2)

有没有办法,比如mutate_at() 中的参数vars()funs(),在mutate_if() 中定义函数,而在之前不需要?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    当然,您可以在 mutate_if 调用中使用匿名函数:

    head(iris)
      Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    1          5.1         3.5          1.4         0.2  setosa
    2          4.9         3.0          1.4         0.2  setosa
    3          4.7         3.2          1.3         0.2  setosa
    4          4.6         3.1          1.5         0.2  setosa
    5          5.0         3.6          1.4         0.2  setosa
    6          5.4         3.9          1.7         0.4  setosa
    
    # mimic use of is_numeric, then add +2 to each column
    iris %>%
        mutate_if(function(x) is.numeric(x),
                  function(x) x + 2) %>%
        head
    
    # Or using the newer syntax (thanks to @akrun):
    iris %>%
        mutate_if(~ is.numeric(.),
                  ~ . + 2) %>%
        head
    
      Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    1          7.1         5.5          3.4         2.2  setosa
    2          6.9         5.0          3.4         2.2  setosa
    3          6.7         5.2          3.3         2.2  setosa
    4          6.6         5.1          3.5         2.2  setosa
    5          7.0         5.6          3.4         2.2  setosa
    6          7.4         5.9          3.7         2.4  setosa
    

    在您的情况下,如果给定非数字数据,您 max 会给出错误,因此我们需要在进行实际测试之前检查它是否为数字,但这样可以正常工作:

    iris %>%
        mutate_if(function(x) if (is.numeric(x)) max(x) > 1 else FALSE,
                  function(x) x / max(x)) %>%
        head
    
      Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    1    0.6455696   0.7954545    0.2028986        0.08  setosa
    2    0.6202532   0.6818182    0.2028986        0.08  setosa
    3    0.5949367   0.7272727    0.1884058        0.08  setosa
    4    0.5822785   0.7045455    0.2173913        0.08  setosa
    5    0.6329114   0.8181818    0.2028986        0.08  setosa
    6    0.6835443   0.8863636    0.2463768        0.16  setosa
    

    【讨论】:

    • 你也可以用iris %&gt;% mutate_if(~ is.numeric(.x) &amp;&amp; max(.x) &gt; 1, f2) %&gt;% head
    【解决方案2】:

    只是要注意,您也可以使用purrr 表示法:

    iris %>%
      mutate_if(~ if (is.numeric(.x)) max(.x) > 1 else FALSE,
                ~ .x / max(.x)) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 2015-12-31
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多