有沒有辦法從字串中洗掉數字僅在最后出現。例子
df
Col A
asdf sfsfsd54 sdfsdfsdf sdfsdfsf654
sfs sfsa5dfgdf sf54 sfsfsgg98
sfs fsdgfdsgd gdfg8
預期產出
df
Col A ColB
asdf sfsfsd54 sdfsdfsdf sdfsdfsf654 asdf sfsfsd54 sdfsdfsdf sdfsdfsf
sfs sfsa5dfgdf sf54 sfsfsgg98 sfs sfsa5dfgdf sf54 sfsfsgg
sfs fsdgfdsgd gdfg8 sfs fsdgfdsgd gdfg
原始資料
structure(list(ColA = c("asdf sfsfsd54 sdfsdfsdf sdfsdfsf654",
"sfs sfsa5dfgdf sf54 sfsfsgg98", "sfs fsdgfdsgd gdfg8")), class = "data.frame", row.names = c(NA,
-3L))
uj5u.com熱心網友回復:
這可以通過以下方式完成gsub:
x <- c("test123", "test12", "test1")
gsub("[0-9] $", "", x)
編輯- 使用您的資料:
df <- structure(list(ColA = c("asdf sfsfsd54 sdfsdfsdf sdfsdfsf654",
"sfs sfsa5dfgdf sf54 sfsfsgg98", "sfs fsdgfdsgd gdfg8")), class = "data.frame", row.names = c(NA,
-3L))
df$ColB <- gsub("[0-9] $", "", df$ColA)
> df
ColA ColB
1 asdf sfsfsd54 sdfsdfsdf sdfsdfsf654 asdf sfsfsd54 sdfsdfsdf sdfsdfsf
2 sfs sfsa5dfgdf sf54 sfsfsgg98 sfs sfsa5dfgdf sf54 sfsfsgg
3 sfs fsdgfdsgd gdfg8 sfs fsdgfdsgd gdfg
uj5u.com熱心網友回復:
這是使用的替代方法str_remove:
library(dplyr)
library(stringr)
df %>%
mutate(ColB = str_remove(ColA, "\\d $"))
ColA ColB
1 asdf sfsfsd54 sdfsdfsdf sdfsdfsf654 asdf sfsfsd54 sdfsdfsdf sdfsdfsf
2 sfs sfsa5dfgdf sf54 sfsfsgg98 sfs sfsa5dfgdf sf54 sfsfsgg
3 sfs fsdgfdsgd gdfg8 sfs fsdgfdsgd gdfg
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408167.html
標籤:
上一篇:字符出現在字串的任何位置?
