Reputation: 51
I am new to R
and would like to know how to remove leading 0
s from a determinate column in a database.
This is the column I have in my df
.
questionn
SI001
SI002
SI003
SI010
and I would like to get something like
questionn
1
2
3
10
I have tried something like this but it doesn't work because of the SI010
library(stringr)
df$questionn <- str_replace_all(df$questionn, 'SQ0', '')
data
df <- data.frame(questionn=c("SI001","SI002","SI003","SI010"),stringsAsFactors = FALSE)
Upvotes: 1
Views: 870
Reputation: 47310
You can remove all characters that are not digits then convert as numeric:
as.numeric(gsub("\\D","",df$questionn))
[1] 1 2 3 10
or as.numeric(str_replace_all(df$questionn,"\\D",""))
for same output.
Upvotes: 1
Reputation: 1354
substr(gsub("SI", "", question$question),
regexpr("[^0]",gsub("SI", "", question$question)),
nchar(gsub("SI", "", question$question)))
Produces:
"1" "2" "3" "10"
The first thing you do is strip out the SI, to get the data in a format of having leading zeros.
Upvotes: 0