r - 向数据框添加其他标头
问题描述
我正在阅读具有三个相关标题行的 .csv 文件。我想读入文件,修改一些变量,然后导出 .csv(保持相同的三个标题行)。
Var1, Var2, VarN
In, Lb, Yrs
Height, Weight, Age
5'8, 180, 40
...
我保存了前两个标题行:
headers <- read.csv(filename, header=F, nrows=2, as.is=T)
我用一个标题读取了其余数据(跳过了我刚刚保存的前两行):
df <- read.csv(filename, skip=2, header=T, as.is=T, stringsAsFactors = FALSE)
在对数据进行了一些修改之后,我想重新添加两个标题。使用 rbind 会导致错误,因为名称不匹配。行数保持不变(没有创建新行)。感谢您的任何提示!
解决方案
#First write your headers to csv
write.table(x = mtcars[1:3,],
file = "test.csv",
col.names = TRUE,
row.names = FALSE,
sep = ",",
append = FALSE)
#Then write your modified data
write.table(x = mtcars[-(1:3),] * 2000,
file = "test.csv",
col.names = FALSE, #We've written this the first time
row.names = FALSE,
sep = ",",
append = TRUE) #add to an existing file
推荐阅读
- angular - 如何在Angular2 +中制作自定义指令以在数字之间给出?
- python - 如何将 jinja 值设置为 html 标签
- node.js - npm 脚本因 sh: 1 失败:
: 在 docker 容器中找不到 - android - 一台设备中的电话身份验证 Firebase 错误
- javascript - 在 ES6 中返回对象内部方法的数据
- javascript - res.redirect("/"); 此代码不起作用,并且在 chrome 检查中显示错误 302
- python - 如何反转未知维度的numpy数组?
- mysql - 如何解决OctoberCMS 数据库丢失?
- vue.js - 在 vuex 中存储敏感信息
- java - 使用 Java 流从字符串数字列表中查找最大数字