Skip to content

[Fwd: Excluding data with apply]

2 messages · Christian Kamenik, Dimitris Rizopoulos

#
Dear all,

I've got many responses to my initial question, which is stated below. 
However, from those responses it has become clear that I need to 
rephrase my problem. All responses dealt with subscripting the data 
matrix before 'apply' is run on it. But this is not want I wanted to do.
'apply' cycles through rows or columns of a matrix, and runs a function 
on each row or column individually. Now, instead of focusing on each 
individual row or column, I want to get rid of these rows or columns, 
and run the function on the remaining matrix.
I could do this with a for loop, such as:

x<-matrix(rnorm(100),20,5)
for (i in 1:ncol(x)) print(mean(x[,-i]))

But for more complex problems this becomes tedious...

Any ideas would be highly appreciated, Christian

  
    
#
you can use something like the following:

# your matrix
mat <- matrix(rnorm(20), 5, 4)

# an indicator matrix specifying which columns
# you want to exclude each time
ind <- matrix(sample(1:3, 18, TRUE), ncol = 3)

apply(ind, 1, function (i) mean(mat[, -i]))

where you may change mean() with whatever function or calculation you're 
interested in.


I hope it helps.

Best,
Dimitris
Christian Kamenik wrote: