Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to keep leading zero when importing a csv file in R?

When I write a .csv file from R where my group names start with a leading zero value, the leading zeros are maintained. However when I import the .csv the leading zeros are dropped and the group names are converted to integers. How can I keep the leading zero in my group names when I import a .csv file in R?

Example

df <- data.frame(matrix(ncol = 1, nrow = 3))
colnames(df)[1] <- 'site'
df$site <- c('01','02','03')
str(df) # the site name has a character class and the leading zeros are maintained
write.csv(df,'test.csv', row.names = FALSE) # I opened in notepad to verify that the leading zeros are maintained

df2 <- read.csv('test.csv')
str(df2) # the site name is integer class and leading zeros have been dropped

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Specify the column as "character" .

read.csv("test.csv", colClasses = c(site = "character"))
##   site
## 1   01
## 2   02
## 3   03

If you don’t have any other columns or if the other columns are also character this could be shortened to:

read.csv("test.csv", colClasses = "character")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading