如何在特定列范围内将函数应用于列表的每个元素?

时间:2017-09-13 14:38:09

标签: r functional-programming purrr

给出具有不同列数的矩阵列表:

set.seed(123)
a <- replicate(5, matrix(runif(25*30), ncol=25) , simplify=FALSE)
b <- replicate(5, matrix(runif(30*30), ncol=30) , simplify=FALSE)
list.of.matrices <- c(a,b)

如何应用函数式编程原则(即使用purrr包)来操作特定范围的列(即第8行,从第2列到列的末尾)?

map(list.of.matrices[8, 2:ncol(list.of.matrices)], mean)

以上回报:

Error in 2:ncol(list.of.matrices) : argument of length 0

2 个答案:

答案 0 :(得分:3)

map_dbl确保返回的值为numeric和double。 ~.是指定要应用的函数的简化方法。

library(purrr)

map_dbl(list.of.matrices, ~mean(.[8, 2:ncol(.)]))
[1] 0.4377532 0.5118923 0.5082115 0.4749039 0.4608980 0.4108388 0.4832585 0.4394764 0.4975212 0.4580137

基本R等价物是

sapply(list.of.matrices, function(x) mean(x[8, 2:ncol(x)]))
[1] 0.4377532 0.5118923 0.5082115 0.4749039 0.4608980 0.4108388 0.4832585 0.4394764 0.4975212 0.4580137

答案 1 :(得分:1)

使用base-R中的Map函数的基本R解决方案:

Map(function(x){mean(x[8,2:ncol(x)])},list.of.matrices)

#[[1]]
#[1] 0.4377532

#[[2]]
#[1] 0.5118923

#[[3]]
#[1] 0.5082115

#[[4]]
#[1] 0.4749039

#[[5]]
#[1] 0.460898

#[[6]]
#[1] 0.4108388

#[[7]]
#[1] 0.4832585

#[[8]]
#[1] 0.4394764

#[[9]]
#[1] 0.4975212

#[[10]]
#[1] 0.4580137
相关问题