定义从多个向量顺序获取参数的函数

时间:2017-01-23 20:29:08

标签: r function

了解添加如何对组件起作用:

a<-1:3
a+a  #Gives (1+1), (2+2), (3+3)

我考虑过在参数长度上使用循环或将它们转换为data.frame然后使用apply,但我有直觉有一种更有效的方法来解决这个问题。

具体来说,我想计算忽略零值的每组组件的平均值,如下所示:

function(x) {
  mean(x[x!=0])
}

x之外,它将是任意数量参数的第i个组成部分。

2 个答案:

答案 0 :(得分:2)

如果我们需要从多个向量顺序执行此操作

Reduce(`+`, listofvectors)

rbindcbind创建matrix,然后执行colSumsrowSums

colSums(m1)

更新

关于问题的第二部分(不清楚),是否要在mean中获取vectorlist,不包括0值

sapply(listofvectors, function(x) mean(x[x!=0]))

或者,如果我们需要mean中的matrix元素序列(由rbind vector s创建),那么replace 0使用NA的值,并使用colMeans

获取na.rm = TRUE
colMeans(replace(m1, m1==0, NA), na.rm = TRUE)
colMeans(replace(m2, m2==0, NA), na.rm = TRUE)
#[1]  6  7  8  9 10 11 12 13 14 15

注意:colMeansmatrix方法是矢量化的。这里没有循环

数据

a1 <- 1:5
b1 <- 6:10
c1 <- 11:15
listofvectors <- list(a1, b1, c1)
m1 <- rbind(a1, b1, c1)
m2 <- rbind(1:10, 11:20)

答案 1 :(得分:2)

如果我理解正确,mapply或其包装Map在这里可以很好地运作。

mapply(function(...) {temp <- c(...); mean(temp[temp != 0])}, 1:10, 11:20)
[1]  6  7  8  9 10 11 12 13 14 15

使用mapply,给定函数应用于每个向量的第一个元素的集合,然后是第二个元素的集合,依此类推。该函数使用c创建一个新向量,然后计算所有非零元素的均值。该函数返回一个原子向量。

Map(function(...) {temp <- c(...); mean(temp[temp != 0])}, 1:10, 11:20)

返回一个列表。这可以包含在unlist中以返回向量。

相关问题