Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Find every location of a string in a 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 instance of a string, say "jan". I can see the hacky solution of running through each slot in the df and checking to see if it =="jan", but there's surely a proper and easier way to do it. Ideally I'd like to get the results returned as a list of coordinates.

Thank you for any help!

like image 775
jdfinch3 Avatar asked Oct 22 '14 04:10

jdfinch3


2 Answers

The function which has an argument called arr.ind which will give you a 2-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
like image 76
Ricardo Saporta Avatar answered Nov 15 '22 16:11

Ricardo Saporta


Firstly, the set of strings to test, can be obtained by:

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

Then, e.g. for the first element, "jan", the location of instances can be given by:

which(xxx == mnths[1], arr.ind = TRUE)
like image 30
atesghnagfbvgfr Avatar answered Nov 15 '22 17:11

atesghnagfbvgfr