Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a Pattern in R

I am trying to clean some data. Below is an example of my data.

   test1          test2         test3    
 jsb cjn       kd N069W j        N9DSW 

I want to indicate what column has the pattern N0{num}{num}W in it. The {num} part can be any number between 0-9. This pattern can also appear anywhere in the string. Hence in this case my results would be as follows.

   test1          test2         test3     col
 jsb cjn       kd N069W j        N9DSW      2

Thanks in advance for any help.

like image 810
Fiona Avatar asked Jun 01 '26 20:06

Fiona


1 Answers

We loop through the columns, use grepl to get a logical index and then with max.col get the column index of each row

max.col(data.frame(lapply(df1, grepl, pattern = "N0\\d{2}W")))
#[1] 2

data

df1 <- structure(list(test1 = "jsb cjn", test2 = "kd N069W j", 
 test3 = "N9DSW"), class = "data.frame", row.names = c(NA, 
 -1L))
like image 50
akrun Avatar answered Jun 03 '26 15:06

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!