Skip to content

tapply to data.frame or matrix

3 messages · Jannis, Rui Barradas, arun

#
Dear R users, 


imagine i have a dataframe and an indexing vector with the length of the 
amount of columns of the dataframe. Is there any convenient way to 
combine the colums of the dataframe into vectors (or straight away apply 
fundtions to these subsets) according to the indexing vector in a 
similar manner to the tapply function? 

For example, in the follwoing case, I would like to combine columns 1 
and two into one vector, and columns 3-4 into another: 

test???? = as.data.frame(matrix(1:20, ncol = 5, nrow=4)) 
test.ind =c(1,1,2,2,2) 


Thanks a lot! 
Jannis
#
Hello,

Here's a way.

test <- as.data.frame(matrix(1:20, ncol = 5, nrow=4))
test.ind <- c(1,1,2,2,2)

lapply(split(colnames(test), test.ind), function(x) unlist(test[, x]))

Hope this helps,

Rui Barradas
Em 04-09-2012 15:40, Jannis escreveu:
#
Hi,
Here's another way:
testagg<-aggregate(colnames(test),list(test.ind),function(x) test[,x])
list(unlist(testagg[,2][1]),unlist(testagg[,2][2]))
#[[1]]
#0.V11 0.V12 0.V13 0.V14 0.V21 0.V22 0.V23 0.V24 
??? 1???? 2???? 3???? 4???? 5???? 6???? 7???? 8 

#[[2]]
#1.V31 1.V32 1.V33 1.V34 1.V41 1.V42 1.V43 1.V44 1.V51 1.V52 1.V53 1.V54 
?#?? 9??? 10??? 11??? 12??? 13??? 14??? 15??? 16??? 17??? 18??? 19??? 20 
A.K.




----- Original Message -----
From: Rui Barradas <ruipbarradas at sapo.pt>
To: Jannis <bt_jannis at yahoo.de>
Cc: r-help <r-help at r-project.org>
Sent: Tuesday, September 4, 2012 11:30 AM
Subject: Re: [R] tapply to data.frame or matrix

Hello,

Here's a way.

test <- as.data.frame(matrix(1:20, ncol = 5, nrow=4))
test.ind <- c(1,1,2,2,2)

lapply(split(colnames(test), test.ind), function(x) unlist(test[, x]))

Hope this helps,

Rui Barradas
Em 04-09-2012 15:40, Jannis escreveu:
______________________________________________
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.