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
>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")