Unimplemented type list when trying to write.table

别等时光非礼了梦想. 提交于 2019-12-02 18:56:23

As mentioned in the comments, you should be able to do something like this (untested) to get "flatten" your list into a character vector:

output$Title <- vapply(output$Title, paste, collapse = ", ", character(1L))

As also mentioned, if you wanted to try the unlist approach, you could "expand" each row by the individual values in output$Title, something like this:

x <- vapply(output$Title, length, 1L)          ## How many items per list element
output <- output[rep(rownames(output), x), ]   ## Expand the data frame
output$Title <- unlist(output$Title, use.names = FALSE)  ## Replace with raw values
Shalini Baranwal

Do this, irrespective of how many columns you have:

df <- apply(df,2,as.character)

Then do write.csv.

There is a new function (introduced in november 2016) in data.table package that handles writing a data.table object to csv quite well, even in those cases when a column of the data.table is a list.

fwrite(data.table, file ="myDT.csv")
Ravi kumar

Another easy solution. Maybe one or more columns are of type list, so we need convert them to "character" or data frame. So there are two easy solutions

  1. Convert each column "as.character" using--

    df$col1 = as.character(df$col1)

    df$col2 = as.character(df$col2)

    .......and so on

  2. The best one convert df in to a "matrix"

    df = as.matrix(df)

now write df into csv. Works for me.

K.Pascal

Assuming

  • the path you want to save to is Path, i.e. path=Path

  • df is the dataframe you want to save,

follow those steps:

  1. Save df as txt document:

    write.table(df,"Path/df.txt",sep="|")
    
  2. Read the text file into R:

    Data = read.table("Path/df.txt",sep="|")
    
  3. Now save as csv:

    write.csv(Data, "Path/df.csv")
    

That's it.

Those are all elegant solutions.

For the curious reader who would prefer some R-code to ready made packages , here's an R-function that returns a non-list dataframe that can be exported and saved as .csv.

output is the "troublesome" data frame in question.

df_unlist<-function(df){

df<-as.data.frame(df)

nr<-nrow(df)

c.names<-colnames(df)

lscols<-as.vector(which(apply(df,2,is.list)==TRUE))

if(length(lscols)!=0){

for(i in lscols){

temp<-as.vector(unlist(df[,i]))

if(length(temp)!=nr){

adj<-nr-length(temp)

temp<-c(rep(0,adj),temp)

}

df[,i]<-temp

} #end for

df<-as.data.frame(df)

colnames(df)<-c.names
}
return(df)
}

Apply the function on dataframe "output" :

newDF<-df_unlist(output)

You can next confirm that the new (newDF) data frame is not 'listed' via apply(). This should successfully return FALSE.

apply(newDF,2,is.list)         #2 for column-wise step.

Proceed to save the new dataframe, newDF as a .csv file to a path of your choice.

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