简体   繁体   English

如何将数据帧写入 csv 文件?

[英]How to make write a data frame to a csv file?

I am making a data frame where one column is a major, and the second column is the list of courses in the major.我正在制作一个数据框,其中一列是专业,第二列是专业的课程列表。

df <- data.frame(majors = majors) df[,"courses"] <- courses

where majors is 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 saying "Error in write.table(df, "Majors_and_Courses.csv", row.names = FALSE, : unimplemented type 'list' in 'EncodeElement'"我收到一条错误消息,提示“write.table 中的错误(df,“Majors_and_Courses.csv”,row.names = FALSE,:“EncodeElement”中未实现的类型“list”)

I suspect that you were creating a data.table or similar, since df[,"courses"] <- courses would otherwise give you a warning.我怀疑您正在创建 data.table 或类似名称,因为df[,"courses"] <- courses否则会给您一个警告。

Solution using data.table:使用 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)

Unlisting beforehand would change the length, unlisting after adding it to the data table would export the "c(...)" structure.预先取消列出会更改长度,将其添加到数据表后取消列出将导出“c(...)”结构。 You can change the separator for the nested list the way you wish, but I discourage you to reuse the separator of the file that you are exporting ("," in this case) to avoid confusion.您可以按照您希望的方式更改嵌套列表的分隔符,但我不鼓励您重复使用要导出的文件的分隔符(在这种情况下为“,”)以避免混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM