【问题标题】:dplyr mutate rowwise max of range of columnsdplyr 改变列范围的行最大值
【发布时间】:2016-01-03 20:55:44
【问题描述】:

我可以使用以下内容返回最多 2 列

newiris<-iris %>%
 rowwise() %>%
 mutate(mak=max(Sepal.Width,Petal.Length))

我想做的是在一系列列中找到最大值,所以我不必像这样命名每个列

newiris<-iris %>%
 rowwise() %>%
 mutate(mak=max(Sepal.Width:Petal.Length))

有什么想法吗?

【问题讨论】:

  • 使用dplyr 1.0.1,您的第二个示例完美运行。

标签: r dplyr


【解决方案1】:

这是一个 base-R 解决方案:可以使用 subset() 选择一系列列名。可以使用transform() 和apply() 的组合添加逐行最大值。

newiris <- transform(iris, mak = apply(subset(iris, select=Sepal.Width:Petal.Length), 1, max))

【讨论】:

    【解决方案2】:

    目前(dplyr 1.0.2),这可行:

    newiris<-iris %>%
     rowwise() %>%
     mutate(mak=max(c_across(Sepal.Width:Petal.Length)))
    

    这还允许您使用选择助手(starts_with 等)。

    【讨论】:

    • 如果你想要包含最大值的列的索引,你也可以将max()替换为which.max()
    【解决方案3】:

    一种方法是将数据通过管道传输到 select 然后调用 pmax 使用使 pmax 按行排列的函数(这与 @inscaven 使用 do.call 的答案非常相似,不幸的是没有 rowMaxs R 中的函数,所以我们必须使用函数来使pmax 按行排列——下面我使用了purrr::pmap)

    library(dplyr)
    library(purrr)
    
    # to get the value of the max
    iris$rowwisemax <- iris %>% select(Sepal.Width:Petal.Length) %>% pmap(pmax) %>% as.numeric
    
    # to get the argmax
    iris$whichrowwisemax <- iris %>% select(Sepal.Width:Petal.Length) %>% {names(.)[max.col(.)]}
    
    

    【讨论】:

    • 谢谢! {names(.)[max.col(.)]} 是我想要的。但是,这种语法是什么?请给我指点这个 {}-syntax 的文档,好吗?我没见过。
    • 当您在表达式中使用嵌套函数时,@PaulSchmidt magrittr 有一个“第一个参数规则”,将 {} 放在表达式周围会阻止它。参见例如magrittr.tidyverse.org/reference/pipe.html#arguments
    【解决方案4】:

    使用 rlang 和 quasiquotation 我们有另一个 dplyr 选项。首先,获取我们要为其计算并行最大值的行名:

    iris_cols <- iris %>% select(Sepal.Length:Petal.Width) %>% names()
    

    然后我们可以使用!!! 和rlang::syms 来计算这些列的每一行的并行最大值:

    iris %>%
      mutate(mak=pmax(!!!rlang::syms(iris_cols)))
    
    • rlang::syms 接受字符串输入(列名),并将其转换为符号
    • !!! 取消引用并拼接它的参数,这里是列名

    这给出了:

        Sepal.Length Sepal.Width Petal.Length Petal.Width    Species mak
    1            5.1         3.5          1.4         0.2     setosa 5.1
    2            4.9         3.0          1.4         0.2     setosa 4.9
    3            4.7         3.2          1.3         0.2     setosa 4.7
    4            4.6         3.1          1.5         0.2     setosa 4.6
    5            5.0         3.6          1.4         0.2     setosa 5.0
    

    h/t:https://stackoverflow.com/a/47773379/1036500

    【讨论】:

      【解决方案5】:

      似乎@akrun 的答案仅解决了您可以输入所有变量名称的情况,无论是直接使用 mutate 和 mutate(pmax_value=pmax(var1, var2)) 还是使用惰性评估和 mutate_ 和 interp via mutate_(interp(~pmax(v1, v2), v1=as.name(var1), v2=as.name(var2)).

      如果您想使用冒号语法 Sepal.Length:Petal.Width 或者如果您碰巧有一个带有列名的向量,我可以看到两种方法。

      第一个更优雅。您整理数据并在分组时取最大值:

      data(iris)
      library(dplyr)
      library(tidyr)
      
      iris_id = iris %>% mutate(id=1:nrow(.))
      iris_id %>%
        gather('attribute', 'value', Sepal.Length:Petal.Width) %>%
        group_by(id) %>%
        summarize(max_attribute=max(value)) %>%
        right_join(iris_id, by='id') %>%
        head(3)
      ## # A tibble: 3 × 7
      ##      id max_attribute Sepal.Length Sepal.Width Petal.Length Petal.Width Species
      ##   <int>         <dbl>        <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
      ## 1     1           5.1          5.1         3.5          1.4         0.2  setosa
      ## 2     2           4.9          4.9         3.0          1.4         0.2  setosa
      ## 3     3           4.7          4.7         3.2          1.3         0.2  setosa
      

      更难的方法是使用插值公式。如果您有一个带有要最大化的变量名称的字符向量,或者如果您的表格太高/太宽而无法整理,这很好。

      # Make a character vector of the names of the columns we want to take the
      # maximum over
      target_columns = iris %>% select(-Species) %>% names
      ## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"
      
      # Make a vector of dummy variables that will take the place of the real
      # column names inside the interpolated formula
      dummy_vars = sapply(1:length(target_columns), function(i) sprintf('x%i', i))
      ## [1] "x1" "x2" "x3" "x4"
      
      # Paste those variables together to make the argument of the pmax in the
      # interpolated formula
      dummy_vars_string = paste0(dummy_vars, collapse=',')
      ## [1] "x1,x2,x3,x4"
      
      # Make a named list that maps the dummy variable names (e.g., x1) to the
      # real variable names (e.g., Sepal.Length)
      dummy_vars_list = lapply(target_columns, as.name) %>% setNames(dummy_vars)
      ## $x1
      ## Sepal.Length
      ##
      ## $x2
      ## Sepal.Width
      ## 
      ## $x3
      ## Petal.Length
      ##
      ## $x4
      ## Petal.Width
      
      # Make a pmax formula using the dummy variables
      max_formula = as.formula(paste0(c('~pmax(', dummy_vars_string, ')'), collapse=''))
      ## ~pmax(x1, x2, x3, x4)
      
      # Interpolate the formula using the named variables
      library(lazyeval)
      iris %>%
        mutate_(max_attribute=interp(max_formula, .values=dummy_vars_list)) %>%
        head(3)
      ##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species max_attribute
      ## 1          5.1         3.5          1.4         0.2  setosa           5.1
      ## 2          4.9         3.0          1.4         0.2  setosa           4.9
      ## 3          4.7         3.2          1.3         0.2  setosa           4.7
      

      【讨论】:

        【解决方案6】:

        为了在使用dplyr 时选择某些列而不输入全名,我更喜欢subset 函数中的select 参数。

        你可以像这样得到想要的结果:

        iris %>% subset(select = 2:4) %>% mutate(mak = do.call(pmax, (.))) %>%
          select(mak) %>% cbind(iris)
        

        【讨论】:

        • 我认为可以使用select( 2:4 ) 而不是subset( select = 2:4 )。
        【解决方案7】:

        可以用pmax代替rowwise()

        iris %>%
              mutate(mak=pmax(Sepal.Width,Petal.Length, Petal.Width))
        

        如果我们想引用存储在vector 中的列名,我们可以使用library(lazyeval) 中的interp。

        library(lazyeval)
        nm1 <- names(iris)[2:4]
        iris %>% 
             mutate_(mak= interp(~pmax(v1), v1= as.name(nm1)))
        

        【讨论】:

        • 关于 pmax 的好主意。知道如何仅通过参考书挡来找到 3 列中的最大值吗?例如:Sepal.Width 到 Petal.Width?
        • @user2502836 更新了帖子。请检查是否有帮助。
        • 我认为 lazyeval 现在已被弃用。谢谢
        猜你喜欢
        • 2020-07-29
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多