[R] Linked count between matrix columns
Guillaume Chapron
carnivorescience at gmail.com
Thu Jan 15 13:36:59 CET 2009
Hello,
I create this array:
x <- cbind(c(1:4, rep(0,10)), c(rep(0,4), 1:2, rep(3,6), 4,5))
[,1] [,2]
[1,] 1 0
[2,] 2 0
[3,] 3 0
[4,] 4 0
[5,] 0 1
[6,] 0 2
[7,] 0 3
[8,] 0 3
[9,] 0 3
[10,] 0 3
[11,] 0 3
[12,] 0 3
[13,] 0 4
[14,] 0 5
I would like to do the following in vector syntax:
for rows where the first column is not 0, put into the second column
the number of times the value of the first column appears in the
second column of rows where the value in the first row is 0
I'm not sure this sounds super clear, so I will show what I want to get:
[,1] [,2]
[1,] 1 1
[2,] 2 1
[3,] 3 6
[4,] 4 1
[5,] 0 1
[6,] 0 2
[7,] 0 3
[8,] 0 3
[9,] 0 3
[10,] 0 3
[11,] 0 3
[12,] 0 3
[13,] 0 4
[14,] 0 5
So for example, x[3,2] = 6, because length(x[x[,1]==0 & x[,2]==3,2]) = 6
I have tried this:
x[x[,1]!=0,2] <- length(x[x[,1]==0 & x[,2] %in% which(x[,1]!=0),2])
but it does not work correctly as it put the same value in the changed
rows.
Thanks for your help!
Guillaume
More information about the R-help
mailing list