Dear all, 'Apply' is a great thing for running functions on rows or columns of a matrix: X <- rnorm(20, mean = 0, sd = 1) dim(X) <- c(5,4) apply(X,2,sum) Is there a way to use apply for excluding rows or columns from a matrix to run functions on the remaining rows or columns? I know, I could do this with a 'for' loop, but 'apply' would be much easier and quicker, and require less programming... Cheers, Christian
Using indexing and putting a minus sign in front of a vector of column
names that you want to exclude would be a typical approach:
df <- data.frame(a=LETTERS[1:4], b= rnorm(4), c=rnorm(4), d=
letters[5:9])
apply(df[ , -c("a","d")], 2, sum)
(Pretty sure this will run properly but don't have R up an runnign to
test it.)
--
David Winsemius
On Jan 8, 2009, at 5:52 AM, Christian Kamenik wrote:
> Dear all,
>
> 'Apply' is a great thing for running functions on rows or columns
of
> a matrix:
>
> X <- rnorm(20, mean = 0, sd = 1)
> dim(X) <- c(5,4)
> apply(X,2,sum)
>
> Is there a way to use apply for excluding rows or columns from a
> matrix to run functions on the remaining rows or columns? I know, I
> could do this with a 'for' loop, but 'apply' would be much
easier
> and quicker, and require less programming...
>
> Cheers, Christian
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
On Thu, Jan 8, 2009 at 5:52 AM, Christian Kamenik < christian.kamenik@giub.unibe.ch> wrote:> > 'Apply' is a great thing for running functions on rows or columns of a > matrix: > > X <- rnorm(20, mean = 0, sd = 1) > dim(X) <- c(5,4) > apply(X,2,sum) > > Is there a way to use apply for excluding rows or columns from a matrix to > run functions on the remaining rows or columns?X <- matrix(1:30,5,6)> X[,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 6 11 16 21 26 [2,] 2 7 12 17 22 27 [3,] 3 8 13 18 23 28 [4,] 4 9 14 19 24 29 [5,] 5 10 15 20 25 30> X[c(-1,-3,-5),c(-2,-4)][,1] [,2] [,3] [,4] [1,] 2 12 22 27 [2,] 4 14 24 29> apply(X[c(-1,-3,-5),c(-2,-4)],c(1),sum)[1] 63 71> apply(X[c(-1,-3,-5),c(-2,-4)],c(2),sum)[1] 6 26 46 56> apply(X[c(-1,-3,-5),2:4],1,sum)[1] 36 42> apply(X[c(-1,-3,-5),c(1,3,5,6)],2,sum)[1] 6 26 46 56> apply(X[c(-1,-3,-5),c(T,F,T,F,T,T)],2,sum)[1] 6 26 46 56 [[alternative HTML version deleted]]