簡體   English   中英

R-來自dplyr的mutate_if中的自有函數

[英]R - own function in mutate_if from 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)

有沒有一種方法,就像參數vars()funs()mutate_at()在中定義的函數mutate_if()之前,而不是必要的?

當然,您可以在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

只需要注意,您還可以使用purrr表示法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM