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
Linked count between matrix columns
7 messages · Henrique Dallazuanna, Guillaume Chapron
An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20090115/50184f1a/attachment-0001.pl>
Thank you! This is exactly what I wanted. Could you please explain the logic behind your code?
x[,2][x[,1][x[,1] > 0]] <- table(x[,2])[as.character(x[,1][x[,1] > 0])]
An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20090115/d83903d4/attachment-0001.pl>
table(x2)[as.character(x[,1][x[,1] > 0])]
Why do I need as.character() here? I checked it does not work without, but I don't see why. The help says "as.character attempts to coerce its argument to character type". Thanks very much! Guillaume
An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20090115/1b527809/attachment-0001.pl>
Because we want the values in table(x[,2]) where the **names** are as.character(x[,1][x[,1] > 0])], not the positions x[,1][x[,1] > 0])].
Thanks!