0

Here's the problem that I have. In my data, order column has the string values. It includes "01". But, when I read csv file, "01" becomes "1". How to maintain the original datafrmae when I read csv file? Here's my example:


data <- data.frame(a = c(1, 2, 3, 4, 5),
                   b = c(3, 4, 2, 7, 8),
                   order = c("10", "01", "101", "01", "10"),
                   f = c(1, 2, 3, 4, 5),
                   e = c(8, 9, 10, 11, 12))


write.csv(data,"E:/data.csv",row.names=FALSE)
data<-read.csv("E:/data.csv")
Lee
  • 369
  • 1
  • 6
  • 1
    You could set the quoting set to `""` on the `read.csv` then remove the quotes afterward with `gsub`. Not ideal though, I hope somebody has a better solution! – George Savva May 23 '23 at 09:06

1 Answers1

4

There are several solutions for this issue at Specifying colClasses in the read.csv

Here is how to apply the top answer to your example:

library(tidyverse)

data <- data.frame(a = c(1, 2, 3, 4, 5),
                   b = c(3, 4, 2, 7, 8),
                   order = c("10", "01", "101", "01", "10"),
                   f = c(1, 2, 3, 4, 5),
                   e = c(8, 9, 10, 11, 12))


write.csv(data,"~/data.csv",row.names=FALSE)
data <- read.csv("~/data.csv", colClasses = c("order" = "character"))
data
#>   a b order f  e
#> 1 1 3    10 1  8
#> 2 2 4    01 2  9
#> 3 3 2   101 3 10
#> 4 4 7    01 4 11
#> 5 5 8    10 5 12

Created on 2023-05-23 with reprex v2.0.2

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46