How to make write a data frame to a csv file?

611    Asked by AnushriSingh in Data Science , Asked on May 18, 2021

 I am forming a data frame where one column is named as a major, and the second column is the list of courses in the major.

df <- data.frame(majors = majors)

df[, "courses"] <- courses, where majors are a vector and courses, is a list of lists. When I try to write using

write.csv(df, "Majors_and_Courses.csv", row. names = FALSE)

I get an error:

"Error in write.table(df, "Majors_and_Courses.csv", row.names = FALSE, : unimplemented type 'list' in 'EncodeElement'"

Answered by Abigail Abraham

The perfect solution for unimplemented type 'list' in 'encodeelement' error is to use the data.table:

library(data.table)
dt <- data.table(majors = c("John", "Lisa", "Tim"))
courses <- list(a = list("m","n","o"), b = list("p", "q", "r"), c = list("s", "t", "u"))
dt[,"courses"] <- courses
dt$courses <- vapply(dt$courses, paste, collapse = "; ", character(1L))
write.csv(dt, "Majors_and_Courses.csv", row.names = FALSE)

Your Answer

Interviews

Parent Categories