R variable string replacement in a data frame -
i have dataframe looks follows:
df <- data.frame(one=c("s1_below_10", "s2_below_20"), two=c("s3_above_10","s4_above_10"))
i want replace strings number preceding first underscore. in other words, desired output is
1 3 2 4
i know how can perform replacement (the dataset large). help.
the basic gsub
call like:
gsub("^.+?(\\d+)_.+","\\1",df$one) [1] "1" "2"
which lapply
each column:
data.frame(lapply(df, gsub, pattern="^.+(\\d+)_.+",replacement= "\\1")) 1 2 1 1 3 2 2 4
Comments
Post a Comment