2017-09-13 109 views
0

考虑到与不同的列数的矩阵列表:如何将函数应用于列表中的每个元素,在特定的列范围内?

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行,从第二到列的末尾)?

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

以上的回报:

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

回答

3

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

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当量是使用Map功能

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

基础R溶液碱-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 
相关问题