user394323
user394323

Reputation: 51

how to remove leading 0 from column

I am new to R and would like to know how to remove leading 0s 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

Answers (3)

moodymudskipper
moodymudskipper

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

MSW Data
MSW Data

Reputation: 461

Try:

as.numeric(str_replace_all(df$questionn,"SI0",""))

Upvotes: 3

Adam Warner
Adam Warner

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

Related Questions