format data from a column in a data.frame in R

Asked

Viewed 81 times

-2

How to put zeros on the left in a column of a data.frame. In this case, I would like to format the data so that it has 4 characters. That is, values of 24 would be left 0024.

2 answers

1


You can use the function sprintf, indicating the desired format:

dados <- c(1, 12, 123, 1234, 12345)

> sprintf("%04d", dados)
[1] "0001"  "0012"  "0123"  "1234"  "12345"

Note that the number of characters indicated refers to the minimum; larger values will not be cut.

0

An example using the dplyr

valores_1 <- c('24','25','34','234','0045', '1234')
dados <- data.frame(Coluna1 = valores_1, stringsAsFactors = FALSE)

library(dplyr)

dados %>% mutate( Coluna1 = case_when(
  nchar(Coluna1) == 2 ~ paste0('00',Coluna1),
  nchar(Coluna1) == 3 ~ paste0('0', Coluna1),
  nchar(Coluna1) == 4 ~ Coluna1
))

There are several ways to do this, this is one of them. The nchar of the string size, compare and add the required amount of 0.

Browser other questions tagged

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