【问题标题】:purrr map instead of applypurrr 映射而不是应用
【发布时间】:2019-06-18 20:11:05
【问题描述】:

我正在尝试在我的代码中加入更多管道。通常,我必须分解管道才能使用 apply 函数。然后我发现了咕噜声。但是,我不清楚它是如何工作的。这是我想要的,也是我尝试过的。主要问题是我想要逐行计算。

想要:

apply(mtcars,1,function(x) which.max(x))

有:

mtcars %>% map_dbl(which.max) 

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    如果我们需要按行排列,则使用pmap。根据?pmap

    ... 请注意,数据框是一个非常重要的特殊情况,在这种情况下 pmap() 和 pwalk() 将函数 .f 应用于每一行。 map_dfr()、pmap_dfr() 和 map2_dfc()、pmap_dfc() 分别返回由行绑定和列绑定创建的数据帧。 ...

    pmap_int(mtcars, ~ which.max(c(...)))
    #[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3 4 4 3
    

    另外,在base R 中,这可以通过max.col 轻松高效地完成

    max.col(mtcars, "first")
    #[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3 4 4 3
    

    map 的使用类似于lapply/sapply,它循环遍历每一列并将函数应用于该列。因此,它类似于

    apply(mtcars, 2, which.max)
    

    【讨论】:

    • 谢谢!完美运行。
    • 如果我想要哪个元素 >5 的最大值(列数)怎么办,像这样:apply(mtcars,1,max(which(x>5)))
    • @chachimouchacha 应该是pmap_int(mtcars, ~ max(which(c(...) > 5)))
    • 正在编造数字以适应 mtcars,混合现实与示例!
    猜你喜欢
    • 2017-10-17
    • 2018-10-22
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多