2017-09-13 35 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 
相關問題