Skip to content

Change dataframe-structure

4 messages · David Studer, Bert Gunter, Gabor Grothendieck +1 more

#
P <- paste("P",1:6,sep="")
t(apply(yourdataframe,1,function(x)P[order(x)]))

## result is a mtrix, though.

-- Bert
On Mon, Feb 13, 2012 at 2:07 PM, David Studer <studerov at gmail.com> wrote:

  
    
#
On Mon, Feb 13, 2012 at 5:07 PM, David Studer <studerov at gmail.com> wrote:
First we read the data and then rearrange it into long form (DF) and
turn that into a 2d matrix (tapply):

Lines <- "p1 p2 p3  p4 p5 p6
1   3   2   5   4   6
2   3   1   6   4   5
1   2   3   4   6   5"
DF0 <- read.table(text = Lines, header = TRUE)

DF <-  as.data.frame.table(as.matrix(DF0), stringsAsFactors = FALSE,
	responseName = "Ranks")
tapply(DF[["Var2"]], DF[-2], c)

The result of the last statement is:

    Ranks
Var1 1    2    3    4    5    6
   A "p1" "p3" "p2" "p5" "p4" "p6"
   B "p3" "p1" "p2" "p5" "p6" "p4"
   C "p1" "p2" "p3" "p4" "p6" "p5"