[R] matrix of all difference between rows values
arun
smartpink111 at yahoo.com
Sat Nov 10 23:05:55 CET 2012
HI,
No problem.
You can also use ?aaply() from library(plyr)
dat1<-read.table(text="
a 10
b 9
c 8
d 7
e 6
",sep="",header=FALSE,stringsAsFactors=FALSE)
library(plyr)
res1<-aaply(dat1[1,2],1,"-",toeplitz(dat1[,2]))
res1[upper.tri(res1)]<- -1*res1[upper.tri(res1)]
rownames(res1)<-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
#or
res2<-matrix(mapply("-",dat1[1,2],toeplitz(dat1[,2])),ncol=5)
#or
#res2<- matrix(sapply(toeplitz(dat1[,2]),function(x) dat1[1,2]-x),ncol=5)
res2[upper.tri(res2)]<- -1*res2[upper.tri(res2)]
dimnames(res2)<-dimnames(res1)
identical(res2,res1)
#[1] TRUE
A.K.
----- Original Message -----
From: cleberchaves <cleberchaves at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Saturday, November 10, 2012 2:25 PM
Subject: Re: [R] matrix of all difference between rows values
Thank you very much, arun kirshna!
That's it! I only modified the "res1<-apply(toeplitz(dat1[,2]),1,function(x)
10-x)" for "res1<-apply(toeplitz(dat1[,2]),1,function(x) dat1[1,2]-x)" and
worked very well!
Thanks again!
--
View this message in context: http://r.789695.n4.nabble.com/matrix-of-all-difference-between-rows-values-tp4649191p4649196.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