[R] matrix of all difference between rows values
arun
smartpink111 at yahoo.com
Sun Nov 11 01:37:46 CET 2012
Hi,
Though the results from Rui, and me are similar, may be it differs in other instances.
My result:
dat1<-read.table(text="
a 10
b 9
c 8
d 7
e 6
",sep="",header=FALSE,stringsAsFactors=FALSE)
res1<-apply(toeplitz(dat1[,2]),1,function(x) 10-x)
res1[upper.tri(res1)]<- -1*res1[upper.tri(res1)]
row.names(res1)<-dat1[,1]
colnames(res1)<-dat1[,1]
res1
# a b c d e
#a 0 -1 -2 -3 -4
#b 1 0 -1 -2 -3
#c 2 1 0 -1 -2
#d 3 2 1 0 -1
#e 4 3 2 1 0
Rui's solution:
t(outer(Table1[,1],Table1[,1],"-"))
# a b c d e
#a 0 -1 -2 -3 -4
#b 1 0 -1 -2 -3
#c 2 1 0 -1 -2
#d 3 2 1 0 -1
#e 4 3 2 1 0
I guess ?expand.grid() might also help you.
dat2<-expand.grid(dat1[,2],dat1[,2])
mat1<-matrix(apply(dat2,1,diff),ncol=5)
dimnames(mat1)<-dimnames(res1)
mat1
# a b c d e
#a 0 -1 -2 -3 -4
#b 1 0 -1 -2 -3
#c 2 1 0 -1 -2
#d 3 2 1 0 -1
#e 4 3 2 1 0
A.K.
----- Original Message -----
From: cleberchaves <cleberchaves at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Saturday, November 10, 2012 3:55 PM
Subject: Re: [R] matrix of all difference between rows values
Mmmm...
Actually, Rui Barradas is the right!
Arun kirshna, yours script has an error. That repeat the same set of numbers
in all columns...
Anyway, thanks for both!
--
View this message in context: http://r.789695.n4.nabble.com/matrix-of-all-difference-between-rows-values-tp4649191p4649207.html
Sent from the R help mailing list archive at Nabble.com.
______________________________________________
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.
More information about the R-help
mailing list