Home > Back-end >  Limiting characters in cells to 32767 while exporting data to a .csv file
Limiting characters in cells to 32767 while exporting data to a .csv file

Time:04-26

This is regarding an issue that I'm facing while exporting data to a .csv file. I'm working with a large dataframe in R. It contains few cells with characters greater than 32767, which is apparently the maximum that a cell can accomodate. When I export the data to a .csv file the content of these cells spills over into the next row. The dataframe however looks completely fine once the .csv file is imported into RStudio. Is there a way to limit the number of characters in each cell to 32767 while exporting the data?

CodePudding user response:

Split long strings into n columns with x characters each, for example:

# example data
d <- data.frame(x = c("longstring", "anotherlongstring"))
d
#                   x
# 1        longstring
# 2 anotherlongstring

x = 6
n = 3
res <- read.fwf(file = textConnection(d$x), widths = rep(x, n))
res
#       V1     V2    V3
# 1 longst   ring  <NA>
# 2 anothe rlongs tring

CodePudding user response:

I found the solution to my question in the answers posted here.

Let's say df is the dataframe which I want to export to a .csv file. The following code does the job

df <- as.data.frame(substr(as.matrix(df), 1, 32767))
write.csv(df, <file>, rownames = FALSE)
  • Related