Friday, 16 August 2013

Substituting the values in a matrix based on the values of other two matrices

Substituting the values in a matrix based on the values of other two matrices

I have two matrices from which values I am subtracting like as follows:
x=read.table("x.txt", sep= "\t", header=FALSE)
9 3 8 2 0
5 4 5 2 1
y=read.table("y.txt", sep= "\t", header=FALSE)
9 7 4 0 5
3 1 0 0 1
xy<-x-y
0 -4 4 2 -5
2 3 5 2 0
I want to substitute the values of xy in that if the value in x>0 and
y==0, the value in xy is substituted by "D" and if x==0 and y>0, it is
substituted by "D". giving me a table such as this:
0 -4 4 D A
2 3 D D 0
I have tried different things, such as a loop:
out <- array(dim=dim(xy))
for (i in 1:length(xy)) {
out[i] <- ifelse(x[i]==0, "D",
ifelse(y[i]==0, "A", xy[i]))
}
but there is something not working, which I attribute to a lack of
understanding in attributing the position of the value for [i].
I also tried using apply, but despite scouring through the internet,
completely failed to understand on how it can be (if it can) be applied to
two dataframes. Any help is much appreciated.

No comments:

Post a Comment