简体   繁体   English

如何在r中使用purrr包应用函数案例

[英]how to do this apply function case using purrr package in r

how to do the following using purrr package? 如何使用purrr包执行以下操作?

set.seed(1)
test <- rnorm(100)
dim(test) <- c(2,5,10)
apply(X = test, MAR = c(1, 2), FUN = which.min)

You can try array_branch or array_tree in purrr package, which coerce multi-dimensional array to a flatten list or hierachical list: 您可以在purrr包中尝试array_brancharray_treepurrr多维数组强制转换为展平列表或层次结构列表:

# array_tree
map(array_tree(test, c(1, 2)), ~ map_int(., which.min))
# [[1]]
# [1]  1  1  4  7 10
#
# [[2]]
# [1] 8 2 1 3 8

# array_branch
map_int(array_branch(test, margin = c(1, 2)), which.min)
# [1]  1  8  1  2  4  1  7  3 10  8

To get the same results like apply : 要获得与apply相同的结果:

x <- map_int(array_branch(test, margin = c(1, 2)), which.min)
y <- array(x, dim = dim(test)[1:2])
# > y
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    1    4    7   10
# [2,]    8    2    1    3    8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM