Outputting a Dataframe in R to a .csv

瘦欲@ 提交于 2019-12-09 05:06:25

问题


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?


回答1:


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.




回答2:


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)



回答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.



来源:https://stackoverflow.com/questions/17291283/outputting-a-dataframe-in-r-to-a-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!