Try this: x[,2][x[,1][x[,1] > 0]] <- table(x[,2])[as.character(x[,1][x[,1] > 0])]
On Thu, Jan 15, 2009 at 10:36 AM, Guillaume Chapron < carnivorescie...@gmail.com> wrote: > 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 > > ______________________________________________ > R-help@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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]
______________________________________________ R-help@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.