Reputation: 406
I'm trying to write a function that accepts (amongst other things) an argument that might be either a vector
, a matrix
, or a data.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)
I'd like to write a function that is generic enough to accept L1
(or L2
), M1
, M2
, D1
, or D2
as an argument, which I'll call myArg
. Inside the function, I want to do something like:
sapply(MyT, function(t) { apply(D2[S > t, ], 2, sum) })
The line above works well. The issue is that I need to make it generic, like:
sapply(MyT, function(t) { apply(myArg[S > t, ], 2, sum) })
However, this code would fail, for instance, if myArg
is L1
or L2
. In this particular case, because I am trying to subset a vector illegally, the error message will read incorrect number of dimensions
. If I fix the subset issue, then I run into the dim(X) must have a positive length
issue, because I can't use apply
on a vector. And so on and so forth...
So, I've landed on trying to do the following:
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
})
I expected this to work, but I'm still getting the Error in apply(myArg[S > t, ], 2, sum) : dim(X) must have a positive length
when I use M2
as myArg
.
I'm confused because dim(M2)
yields [1] 15 2
.
Curious if anyone can shed light on why I get this error when I use M2
as myArg
Upvotes: 0
Views: 77
Reputation: 57696
R has an object framework. It has three of them, in fact (four if you count R6, five if you count proto). So why not make use of them?
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])
Upvotes: 5