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

时间:2021-05-09 14:29:46

Given a list of matrices with different number of columns:

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

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)

How can I apply functional programming principles (i.e. using the purrr package) to operate on a specific range of columns (i.e. 8th row, and from 2nd to the end of columns)?

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

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

The above returns:

以上回报:

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

2 个解决方案

#1


3  

map_dbl makes sure the returned values are numeric and double. ~ and . is a simplified way to specify the function to apply.

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

The base R equivalent is

基数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

#2


1  

Base R solution using the Map function in base-R:

使用base-R中的Map函数的Base 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

#1


3  

map_dbl makes sure the returned values are numeric and double. ~ and . is a simplified way to specify the function to apply.

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

The base R equivalent is

基数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

#2


1  

Base R solution using the Map function in base-R:

使用base-R中的Map函数的Base 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