简体   繁体   中英

how to remove leading 0 from column

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)

尝试:

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM