R - Find each row location in the data frame

I have a data frame that looks like this:

a <- c("jan", "mar", "jan", "feb", "feb") b <- c("feb", "mar", "mar", "jan", "mar") c <- c("jan", "feb", "feb", "jan", "jan") d <- c("jan", "mar", "jan", "feb", "feb") e <- c("feb", "jan", "feb", "mar", "mar") f <- c("jan", "feb", "feb", "jan", "jan") xxx <- data.frame(a,b,c,d,e,f) xxx 

I need to find the location in xxx of each row instance, for example "jan". I can see the hacking solution running through each slot in df and check if it is a "jan", but of course, the right and simple way to do it. Ideally, I would like to get the results returned as a list of coordinates.

Thanks for the help!

+8
search r dataframe
source share
2 answers

The which function has an argument called arr.ind , which will give you a two-column matrix indicating the location of each match

 which(xxx == "jan", arr.ind=TRUE) row col [1,] 1 1 [2,] 3 1 [3,] 4 2 [4,] 1 3 [5,] 4 3 [6,] 5 3 [7,] 1 4 [8,] 3 4 [9,] 2 5 [10,] 1 6 [11,] 4 6 [12,] 5 6 
+8
source share

Firstly, a set of lines for testing can be obtained:

 mnths <- unique(c(t(xxx))) 

Then, for example, for the first jan, the location of the instances can be specified with:

 which(xxx == mnths[1], arr.ind = TRUE) 
+2
source share

All Articles