Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find location of a character and write location to a data frame in r

Suppose this dataframe:

col1<- c('a_b_c_fv', 'ff_g1_h_fv','e_ii_jjjj_fv' )
df <- data.frame(col1)

Want to find the location of the third occurrence of the underscore _ and then write that location back to the data frame. So final result would look like:

df$location <- c(6,8,10) 

How can I do this pleaase?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried

unlist(gregexpr('_', df$col1))[3]

but I only get the first row location.

>Solution :

Because gregexpr outputs a list for each vector element, you need to extract the corresponding values before unlist. One example to extract the information is using sapply.

df$location <- sapply(gregexpr('_', df$col1), `[[`, 3)

df
          col1 location
1     a_b_c_fv        6
2   ff_g1_h_fv        8
3 e_ii_jjjj_fv       10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading