R语言输出csv文件
完成数据分析、描述性统计等运算后,若无法把输出结果导出适配常规办公软件的格式,分析结论就难以对外直观呈现,成果落地展示存在明显阻碍。所以数据输出也尤为重要。为此我们构建一个数据框,并将数据框输出为csv文件。
# 1. 设置随机种子,保证每次生成结果一致
set.seed(123)# 2. 设置保存路径
output_dir <- "G:/学生成绩" # 如果文件夹不存在,则自动创建 if (!dir.exists(output_dir)) { dir.create(output_dir, recursive = TRUE) #创建文件夹 } output_file <- file.path(output_dir, "学生成绩.csv")# 3. 构造数据框
student_name <- c( "张伟", "王芳", "李娜", "刘洋", "陈晨", "杨帆", "赵敏", "黄磊", "周婷", "吴迪", "徐静", "孙浩", "胡鑫", "朱琳", "高峰", "林雪", "何强", "郭佳", "马超", "罗丹", "梁宇", "宋雨", "郑凯", "谢欣", "韩梅", "唐俊", "冯雪", "曹磊", "邓洁", "彭涛", "曾琪", "萧然", "田野", "董慧", "袁博", "潘婷", "蒋明", "蔡宁", "余航", "杜娟", "叶凡", "程曦", "魏然", "苏阳", "白雪", "石磊", "江涛", "邹静", "薛峰", "孟瑶", "秦川", "陆洋", "乔欣", "贾晨", "丁宁", "尹浩", "戴琳", "范宇", "卢婷", "侯斌" ) student_id <- paste0("S", 2026001:2026060) n <- 60 chinese <- round(runif(n, 70, 98), 1) math <- round(runif(n, 65, 100), 1) foreign_language <- round(runif(n, 68, 99), 1) physics <- round(runif(n, 60, 96), 1) chemistry <- round(runif(n, 62, 97), 1) biology <- round(runif(n, 65, 98), 1) politics <- round(runif(n, 70, 96), 1) history <- round(runif(n, 68, 97), 1) geography <- round(runif(n, 66, 98), 1) art <- round(runif(n, 75, 100), 1) pe <- round(runif(n, 70, 100), 1) music <- round(runif(n, 72, 100), 1) information_technology <- round(runif(n, 70, 100), 1)# 4. 生成数据框
student_score <- data.frame( 姓名 = student_name, 学生ID = student_id, 语文 = chinese, 数学 = math, 外语 = foreign_language, 物理 = physics, 化学 = chemistry, 生物 = biology, 政治 = politics, 历史 = history, 地理 = geography, 美术 = art, 体育 = pe, 音乐 = music, 信息技术 = information_technology, check.names = FALSE )# 5. 查看前几行数据
cat("\n========== 学生成绩数据前6行 ==========\n") print(head(student_score))# 6. 保存为 CSV 文件
write.csv( student_score, file = output_file, row.names = FALSE, fileEncoding = "GB18030" )