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?
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