Home > Back-end >  How to keep leading zero when importing a csv file in R?
How to keep leading zero when importing a csv file in R?

Time:08-09

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

CodePudding user response:

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

CodePudding user response:

Define the column type explicitly, for example using vroom. But other packages also provide that functionality. You can determine the column specifications with spec() first.

library(vroom)
spec(vroom('test.csv'
             , delim = ","
             ))
df2 <- vroom('test.csv'
             , delim = ","
             , col_types = cols(
               site = col_character()
             )
             )
  •  Tags:  
  • r
  • Related