繁体   English   中英

在接受向量,矩阵或data.frame作为参数的函数中使用apply

[英]use of apply in a function that accepts vector, matrix, or data.frame as an argument

我正在尝试编写一个函数,该函数接受(除其他事项外)一个参数,该参数可以是vectormatrixdata.frame

set.seed(101)
MyT <- seq(0, 1, 0.1)
S   <- sample(seq(0, 1, 0.01), 15, replace = T)
L1  <- sample(c(0,1), 15, replace = T)
L2  <- sample(c(0,1), 15, replace = T)
M1  <- as.matrix(L1)
M2  <- as.matrix(L1, L2)
D1  <- data.frame(L1)
D2  <- data.frame(L1, L2)

我想编写一个通用性足以接受L1 (或L2 ), M1M2D1D2作为参数的函数,我将其称为myArg 在函数内部,我想执行以下操作:

sapply(MyT, function(t) { apply(D2[S > t, ], 2, sum) })

上面的行效果很好。 问题是我需要使其通用,例如:

sapply(MyT, function(t) { apply(myArg[S > t, ], 2, sum) })

但是,例如,如果myArgL1L2 ,则此代码将失败。 在这种情况下,由于我试图非法子集矢量,因此错误消息将读取incorrect number of dimensions 如果我解决了子集问题,那么我碰到dim(X) must have a positive length问题,因为我不能在向量上使用apply 等等等等...

因此,我着手尝试执行以下操作:

sapply( MyT, function(t) { 
  if (length(dim(myArg)) == 0) sum(myArg[S > t])  # for vector
  else if (dim(myArg)[2] == 1) sum(myArg[S > t, ])  # for single-column matrix or data.frame
  else sapply(myArg[S > t, ], 2, sum)  # for multi-column matrix or data.frame
})

我期望这可以工作,但是我仍然遇到Error in apply(myArg[S > t, ], 2, sum) : dim(X) must have a positive length当我使用M2作为myArg时, Error in apply(myArg[S > t, ], 2, sum) : dim(X) must have a positive length

我很困惑,因为dim(M2)产生[1] 15 2

好奇是否有人可以阐明为什么当我使用M2作为myArg时为什么会出现此错误

R有一个对象框架。 实际上,它有3个(如果计算R6,则为4个,如果计算proto,则为5个)。 那么为什么不利用它们呢?

myFunc <- function(x, ...)
UseMethod("myFunc")

# don't use apply() on data frames unless you know what you're doing
myFunc.data.frame <- function(x, S, t, ...)
sapply(x[S > t, ], myFunc.default)

myFunc.matrix <- function(x, S, t, ...)
apply(x[S > t, ], 2, myFunc.default)

myFunc.default <- function(x, S=1, t=0, ...)
sum(x[S > t])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM