Zero left on R

Asked

Viewed 507 times

2

I have a code that takes a txt file with ";" delimiter and swaps it with "/t". However, in these 90 files, there are fields with id = 01,02,03,04 ... When I change bounders the fields with the id above comes 1,2,3,4,5. It happens that I need these zeros in front of these id.

fns = list.files(patt="\\.txt")

n <- length(fns) # Conta o numero de itens na lista

for (i in 1:n){
  dado1 <- read.table(fns[i], head=T,sep=";",encoding = "UTF-8")
  names(dado1)[grep("ï..ID", names(dado1))] <- "ID"
  names(dado1)[grep("X.U.FEFF.ID", names(dado1))] <- "ID"
  #dado1$FL_INPUT[which( is.na(dado1$FL_INPUT))] <- "1"
  excluir <- c("FL_INPUT", "FL_VALIDACAO_LISTAGEM")
  dado1 <- dado1[,!(names(dado1)%in% excluir)]
  write.table(dado1, fns[i], sep="\t", row.names = FALSE, quote=FALSE, na= "", dec = ",")
}

2 answers

4

Here there are a few options. You could use:

b <- 01
paste0("0",b)

or:

formatC(b, width=2, format="d", flag="0")

which results in:

[1] 1
[1] "01"
[1] "01"
  • Thank you very much bro resolved <3

  • 1

    Good :) don’t forget to accept the answer then

2

You can do this with sprintf:

id <- 1:20
sprintf("%02d", id)
# [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12"
#[13] "13" "14" "15" "16" "17" "18" "19" "20"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.