data processing - R: choose and replace a specific character to the middle of string -


i have dataset looks like:

name            age c_g06_m_15-35   55-64 c_g07_m_15-35   45-54 c_pili_m_36-44  35-44 c_g14_m_15-35   55-64 c_pili_m_15-24  45-54 c_pili_m_25-35  55-64 c_g05_m_15-35   45-54 c_g01_m_15-35   35-44 c_g11_m_15-35   18-24 c_g20_m_15-35   25-34 c_al006_a_15-60 45-54 c_all_f_15-35   35-44 c_south_m_15-24 25-34 

but need "g13", "g10" etc. strings in middle of "name" column, how choose , replace it?

name    age g06     55-64 g07     45-54 pili    35-44 g14     55-64 pili    45-54 pili    55-64 g05     45-54 g01     35-44 g11     18-24 g20     25-34 al006   45-54     35-44 south   25-34 

you can try

df1$name <- sub('[^_]+_([^_]+).*', '\\1', df1$name) df1 #    name   age #1    g06 55-64 #2    g07 45-54 #3   pili 35-44 #4    g14 55-64 #5   pili 45-54 #6   pili 55-64 #7    g05 45-54 #8    g01 35-44 #9    g11 18-24 #10   g20 25-34 #11 al006 45-54 #12   35-44 #13 south 25-34 

data

df1 <- structure(list(name = c("c_g06_m_15-35", "c_g07_m_15-35", "c_pili_m_36-44",  "c_g14_m_15-35", "c_pili_m_15-24", "c_pili_m_25-35", "c_g05_m_15-35",  "c_g01_m_15-35", "c_g11_m_15-35", "c_g20_m_15-35", "c_al006_a_15-60",  "c_all_f_15-35", "c_south_m_15-24"), age = c("55-64", "45-54",  "35-44", "55-64", "45-54", "55-64", "45-54", "35-44", "18-24",  "25-34", "45-54", "35-44", "25-34")), .names = c("name", "age" ), class = "data.frame", row.names = c(na, -13l)) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

c# - Retrieve google contact -

javascript - How to insert selected radio button value into table cell -