Write.csv while maintaining character data type

Hi everyone,

I am trying to use write.csv to export a dataframe.
One of the columns in the dataframe are numbers representing unique identifiers for satellite lidar shots. I have used paste0(shot_number) to convert the data type from a number to a character.
Now when I export the data to csv, the columns data type has changed back to a number and is represented in scientific notation. When I use paste0() again, the numbers are no longer unique.

My question is as follows:
How can I export the dataframe as a csv while maintaining the character datatype of the shot number ID?

Any ideas are greatly appreciated.

When you read the data back in, you can declare the data class to prevent the id being converted to a number.

DF <- data.frame(Code = c("987654321987654321","87654321087654321"), Value = 1:2)
                Code Value
1 987654321987654321     1
2  87654321087654321     2
write.csv(DF, "NumTest.csv", row.names = FALSE)
read.csv("NumTest.csv") #converts to numeric
          Code Value
1 9.876543e+17     1
2 8.765432e+16     2
read.csv("NumTest.csv", colClasses = c("character", "numeric")) #preserves character
                Code Value
1 987654321987654321     1
2  87654321087654321     2
readr::read_csv("NumTest.csv", col_types = "cn") #preserves character with shorthand notation in readr::read_csv
# A tibble: 2 × 2
  Code               Value
  <chr>              <dbl>
1 987654321987654321     1
2 87654321087654321      2
1 Like

Thank you FJCC, you've been a huge help.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.