21

So I'm trying to write a .csv file based on a data frame in R, but for some reason I keep getting the following error:

Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol,  : 
  unimplemented type 'list' in 'EncodeElement

This is what traceback() is giving:

5: write.table(df, file = "df.csv", col.names = NA, 
       sep = ",", dec = ".", qmethod = "double")
4: eval(expr, envir, enclos)
3: eval(expr, p)
2: eval.parent(Call)
1: write.csv(df, file = "df.csv")

Any solution?

riders994
  • 1,246
  • 5
  • 13
  • 33

3 Answers3

31

You can also coerce data frames directly in R:

my.df <- data.frame(lapply(old.df, as.character), stringsAsFactors=FALSE)

CAVEAT: this will coerce your entire dataframe to whatever type you specify. For example, if you want to coerce your dataframe to number, you would replace 'as.characater' with 'as.numeric':

 my.df <- data.frame(lapply(old.df, as.numeric), stringsAsFactors=FALSE)
SummerEla
  • 1,902
  • 3
  • 26
  • 43
  • @SummerEla, what if the list is not of the same length : it gaves me `arguments imply differing number of rows: 2, 3` error – academic.user May 11 '15 at 21:33
  • 1
    @academic.user For data frames, R generally works under the assumption that all the columns you put in a data frame are going to be the same length. For help wrangling your data, try something like this: http://stackoverflow.com/questions/15753091/convert-mixed-length-named-list-to-data-frame – SummerEla May 12 '15 at 22:15
  • 4
    This worked for me as well, with a caveat that `as.character` changes everything to a character column, messing up the digits in my decimals. If you're working with a numeric data.frame try `my.df <- data.frame(lapply(old.df, as.numeric), stringsAsFactors=FALSE)` – slammaster Sep 16 '15 at 14:24
  • Thanks, @slammaster; I updated my answer to incorporate your point. – SummerEla Apr 21 '16 at 18:13
20

One of your columns is of type list, so the data.frame is no longer 2-dimensional and can't be exported to a 2d csv-file.

If you still want to store the list in the resulting output, you might transform it to JSON first. So it becomes an column of type "character" which can be easily exported as one column to csv.

Marcel Hebing
  • 3,072
  • 1
  • 19
  • 22
3

I just had the same issue and instead of using as.character() or as.numeric(), I used as.matrix(), and it kept my character variables character, and my numeric variables numeric, and output the .csv file like a dream.