【问题标题】:Make rowwise operations on a vector of columns对列向量进行逐行操作
【发布时间】:2020-03-16 11:53:41
【问题描述】:

我想了解如何获得在字符串向量中定义的一组列的逐行最小值,即如何使用以下输入获得以下输出:

输入:

t <- data.frame(x= c(1,2,3,4), y= c(2,3,4,5), z = c(4,5,6,7))
vars. <- c('x', 'y')

我的(不工作)建议:

t %>% rowwise %>% mutate(min_x_y = min(vars(vars.)))

输出应该是:

  x y z min_x_y
1 1 2 4       1
2 2 3 5       2
3 3 4 6       3
4 4 5 7       4

【问题讨论】:

  • 除了将列名放在向量中的部分之外,this post 对逐行汇总统计有几个想法
  • 查看dplyr 1.0 的新功能,其中包括across 功能。在最近的SO post 中也进行了讨论。

标签: r dplyr


【解决方案1】:

我们可以使用purrr中的pmap_dbl

library(dplyr)
library(purrr)

t %>% mutate(min_x_y = pmap_dbl(select(., vars.), min))

#  x y z min_x_y
#1 1 2 4       1
#2 2 3 5       2
#3 3 4 6       3
#4 4 5 7       4

基本的 R 版本是

t$min_x_y <- do.call(pmin, t[vars.])

【讨论】:

    【解决方案2】:

    已经建议的方法的另一种替代方法是结合使用整洁的评估和pmin

    # convert character vector of variable names into symbols
    vars. <- c('x', 'y') %>% dplyr::syms()
    
    # use tidy evaluation to pass symbols to pmin inside a mutate call
    t %>% 
      mutate(min_x_y = pmin(!!!vars.))
    #>   x y z min_x_y
    #> 1 1 2 4       1
    #> 2 2 3 5       2
    #> 3 3 4 6       3
    #> 4 4 5 7       4
    

    【讨论】:

      【解决方案3】:

      你可以通过不同的方式做到这一点,一种是;

      t <- data.frame(x= c(1,2,3,4), y= c(2,3,4,5), z = c(4,5,6,7))
      vars. <- c('x', 'y')
      
      t$min_x_Y=t(as.data.frame(t(t)) %>%
        summarise_all(funs(min)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-12
        • 1970-01-01
        • 1970-01-01
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多