R Data frames and R lists are potentially incompatible...
A list is, essentially a vector where each element can be of a different type and length of elements. Meanwhile, a Data frame can be thought of a uniform spreadsheet where each column can store a different type of data, or nonnested lists where each element is of the same length. This last point is important as lists can have unequal lengths, whilst a Data frames do not.
Thus, it may be easier to save the list as an RDS file using saveRDS()
dataDir <- "."
saveRDS( operacions, file.path(dataDir, "files"))
operacions2 <- readRDS(file.path(dataDir, "files"))
this will save it as an R-Object, and similarly, restore the R object later.
If you do want to convert to a data frame you can first convert to a nested data frame, and then fill in the blanks in the data frame. Thus...
require(data.table)
require(plyr)
operacions<-list(list(Nom="Victor",Bolis= c("Negro","azul","verde")),list(Nom="Dani",Lapices=c(1:4)))
str(operacions)
operacionsdf <- lapply(operacions, data.frame, stringsAsFactors = FALSE)
str(operacionsdf)
operacionsdf2 <- rbind.fill(operacionsdf)
str(operacionsdf2)
write.csv2(operacionsdf2, "file.csv",row.names = FALSE)
operacionsdf3 <- read.csv2("file.csv")
str(operacionsdf3)
output:
> require(data.table)
> require(plyr)
> operacions<-list(list(Nom="Victor",Bolis= c("Negro","azul","verde")),list(Nom="Dani",Lapices=c(1:4)))
> str(operacions)
List of 2
$ :List of 2
..$ Nom : chr "Victor"
..$ Bolis: chr [1:3] "Negro" "azul" "verde"
$ :List of 2
..$ Nom : chr "Dani"
..$ Lapices: int [1:4] 1 2 3 4
> operacionsdf <- lapply(operacions, data.frame, stringsAsFactors = FALSE)
> str(operacionsdf)
List of 2
$ :'data.frame': 3 obs. of 2 variables:
..$ Nom : chr [1:3] "Victor" "Victor" "Victor"
..$ Bolis: chr [1:3] "Negro" "azul" "verde"
$ :'data.frame': 4 obs. of 2 variables:
..$ Nom : chr [1:4] "Dani" "Dani" "Dani" "Dani"
..$ Lapices: int [1:4] 1 2 3 4
> operacionsdf2 <- rbind.fill(operacionsdf)
> str(operacionsdf2)
'data.frame': 7 obs. of 3 variables:
$ Nom : chr "Victor" "Victor" "Victor" "Dani" ...
$ Bolis : chr "Negro" "azul" "verde" NA ...
$ Lapices: int NA NA NA 1 2 3 4
> write.csv2(operacionsdf2, "file.csv",row.names = FALSE)
> operacionsdf3 <- read.csv2("file.csv")
> str(operacionsdf3)
'data.frame': 7 obs. of 3 variables:
$ Nom : Factor w/ 2 levels "Dani","Victor": 2 2 2 1 1 1 1
$ Bolis : Factor w/ 3 levels "azul","Negro",..: 2 1 3 NA NA NA NA
$ Lapices: int NA NA NA 1 2 3 4