Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the row and column position of R data frame where the cell value matches a pattern

Tags:

r

I have a dataframe

structure(list(Brand = c("AB", "AC", "AD", "BA", "CB", "CK"), `&TV` = c("0_640", 
"0", "1_340", "0", "0", "0"), `&TV HD` = c("1_500", "0", "0_140", 
"0", "0", "0")), row.names = c(NA, 6L), class = "data.frame")

that looks like this:

  Brand   &TV &TV HD
1    AB 0_640  1_500
2    AC     0      0
3    AD 1_340  0_140
4    BA     0      0
5    CB     0      0
6    CK     0      0

I want to return the row and column value of those cells that has the pattern 1_ in it. For the above example, I want to return

row col
3    2
1    3

I am trying to use grep but was not very successful.

grep(New_Brands_Theme_Combine[,c(1:length(New_Brands_Theme_Combine))], pattern = "1_")

The above gives me the column numbers of the data frame where the pattern is found. How do I get the column numbers along with the row numbers.

like image 556
Apricot Avatar asked Sep 07 '25 00:09

Apricot


1 Answers

One option is loop over the columns of interest ('colnm'), apply the grep to get the position index, set the names of the list with the column index and stack it to a two column data.frame

colnm <- 2:3
out <- stack(setNames(lapply(df1[colnm], grep, pattern = "1_"), colnm))
names(out) <- c("row",  "col")
out
#  row col
#1   3   2
#2   1   3
like image 152
akrun Avatar answered Sep 09 '25 19:09

akrun