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!
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With