Hi, I want to make a data frame which contains the positions of some searched values in another data frame. Like: Dataframe 1: 1 2 3 4 1 2 3 4 2 3 4 1 2 3 4 2 4 1 2 3 2 3 4 1 Let's say I searched on "4", then Dataframe 2 should contain: x y 1 4 1 8 2 3 2 7 3 1 3 7 I have written a routine, but it seems to me that it isn't that perfect: x<- 0 y<- 0 for (j in 1:ncol(df)) { for (i in 1:nrow(df)) { if (df[i,j] == 3) { x <- c(x,i) y <- c(y,j) } } } df2 <- data.frame(x,y) df2 <- df2[-1,] Can someone come up with an elegant/faster solution, because the ultimate goal of this routine is to analyze an jpg image. Kind regards Bart [[alternative HTML version deleted]]
Try this: which(DF1 == 4, arr.ind = TRUE) On 6/24/06, Bart Joosen <bartjoosen at hotmail.com> wrote:> Hi, > > I want to make a data frame which contains the positions of some searched values in another data frame. > > Like: > Dataframe 1: > > 1 2 3 4 1 2 3 4 > 2 3 4 1 2 3 4 2 > 4 1 2 3 2 3 4 1 > > Let's say I searched on "4", then Dataframe 2 should contain: > x y > 1 4 > 1 8 > 2 3 > 2 7 > 3 1 > 3 7 > > I have written a routine, but it seems to me that it isn't that perfect: > x<- 0 > > y<- 0 > > for (j in 1:ncol(df)) { > > for (i in 1:nrow(df)) { > > if (df[i,j] == 3) { > > x <- c(x,i) > > y <- c(y,j) > > } > > } > > } > > df2 <- data.frame(x,y) > > df2 <- df2[-1,] > > Can someone come up with an elegant/faster solution, because the ultimate goal of this routine is to analyze an jpg image. > > Kind regards > > Bart
I'll suggest an algorithm with a little code but haven't actually tried it. R loves vector/matrix operations (and, incidentally, you probably ought to be using matrices here and not data frames, particularly if the images are "large"). Here is your matrix from your example (I'll call this x) 1 2 3 4 1 2 3 4 2 3 4 1 2 3 4 2 4 1 2 3 2 3 4 1 Create two more matrices (I'll call the mask1 and mask2): 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 To find the coordinates in x where x is 4: coords <- cbind(mask1[x==4], mask2[x==4]) Jay ------------------------------------------------- Your original query was: Hi, I want to make a data frame which contains the positions of some searched values in another data frame. Like: Dataframe 1: 1 2 3 4 1 2 3 4 2 3 4 1 2 3 4 2 4 1 2 3 2 3 4 1 Let's say I searched on "4", then Dataframe 2 should contain: x y 1 4 1 8 2 3 2 7 3 1 3 7 I have written a routine, but it seems to me that it isn't that perfect: < CODE DELETED BY JAY TO SAVE SPACE> Can someone come up with an elegant/faster solution, because the ultimate goal of this routine is to analyze an jpg image. Kind regards Bart -- John W. Emerson (Jay) Assistant Professor of Statistics Yale University http://www.stat.yale.edu/~jay [[alternative HTML version deleted]]