Omphalodes Verna
2012-Feb-04 14:11 UTC
[R] eliminate rows with all NA values in matrix of special class
Dear list!
I have a problem with eliminate rows with all NA values in matrix of special
class ("my.class"). Belowe is a example:
#class definition
setClass("my.class", representation(ID="character",
years="integer", my.mat="matrix"))
data.1 <- new("my.class", ID = c("tA", "tB",
"tC"), years = as.integer(c(2000, 2005, 2010, 2015, 2020)),
my.mat = matrix(c(NA, 1, NA, NA, 4, 3, 1, 5, 6, 2, NA, 5, 1, NA, 3), ncol = 3,
byrow = TRUE))
data.1
#selection definition
setMethod("[", c("my.class", "numeric",
"character"), function(x, i, j, ..., drop=TRUE) {
IDx <- match(j, x@ID)
if (any(is.na(IDx))) stop("invalid 'j'")
initialize(x, ID = x@ID[IDx], years = x@years[i], my.mat = x@my.mat[i, IDx,
drop=FALSE])})
setMethod("[", c("my.class", "missing",
"character"), function(x, i, j, ..., drop=TRUE) {
x[(1:length(x@years)), j, ..., drop=drop]
})
setMethod("[", c("my.class", "missing",
"numeric"), function(x, i, j, ..., drop=TRUE) {
x[, x@ID[j], ..., drop=drop]
})
#R output
data.1[, c(1,3)] # Extract Part of an Object (column 1 & 3)
An object of class “my.class”
Slot "ID":
[1] "tA" "tC"
Slot "years":
[1] 2000 2005 2010 2015 2020
Slot "my.mat":
[,1] [,2]
[1,] NA NA
[2,] NA 3
[3,] 1 6
[4,] 2 5
[5,] 1 3
But I would like to get like this:
data.1[,c(1,3)] # Extract Part of an Object (column 1 & 3)
An object of class “my.class”
Slot "ID":
[1] "tA" "tC"
Slot "years": ### without year 2000 because there is no data (all are
NA)
[1] 2005 2010 2015 2020
Slot "my.mat": ### without first row because there is no data (all are
NA)
[,1] [,2]
[1,] NA 3
[2,] 1 6
[3,] 2 5
[4,] 1 3
With 'apply' I define which row has all NA values:
which(apply(MATRIX, 1, function(x) all(is.na(x))))
Please give any suggestions. Thanks a lot, OV
[[alternative HTML version deleted]]