How to remove all characters before "p", and "p" itself, in all strings of v1 as in data frame below.
如何在v1的所有字符串中删除“p”和“p”本身之前的所有字符,如下面的数据框中所示。
df1 <- data.frame(v1 = c("m0p1", "m5p30", "m11p20", "m59p60"))
How to remove all characters after "p" and "p" itself? Thank you
如何删除“p”和“p”后面的所有字符?谢谢
3 个解决方案
#1
You could also do
你也可以这样做
sub('^[^p]*p', '', df1$v1)
#[1] "1" "30" "20" "60"
Or
sub('p.*$', '', df1$v1)
#[1] "m0" "m5" "m11" "m59"
#2
You can use gsub
你可以使用gsub
# Remove everything before p
gsub("^.*?p(.*)","\\1",df1$v1,perl=TRUE)
#[1] "1" "30" "20" "60"
# Remove everything after p
gsub("(.*)?p.*$","\\1",df1$v1,perl=TRUE)
# [1] "m0" "m5" "m11" "m59"
#3
After p:
gsub('.*(?<=p)(\\d+)','\\1',df1$v1,perl=T)
Before p:
gsub('(.*)(?=p).*','\\1',df1$v1,perl=T)
#1
You could also do
你也可以这样做
sub('^[^p]*p', '', df1$v1)
#[1] "1" "30" "20" "60"
Or
sub('p.*$', '', df1$v1)
#[1] "m0" "m5" "m11" "m59"
#2
You can use gsub
你可以使用gsub
# Remove everything before p
gsub("^.*?p(.*)","\\1",df1$v1,perl=TRUE)
#[1] "1" "30" "20" "60"
# Remove everything after p
gsub("(.*)?p.*$","\\1",df1$v1,perl=TRUE)
# [1] "m0" "m5" "m11" "m59"
#3
After p:
gsub('.*(?<=p)(\\d+)','\\1',df1$v1,perl=T)
Before p:
gsub('(.*)(?=p).*','\\1',df1$v1,perl=T)