首页 > 解决方案 > 向数据框添加其他标头

问题描述

我正在阅读具有三个相关标题行的 .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 会导致错误,因为名称不匹配。行数保持不变(没有创建新行)。感谢您的任何提示!

标签: r

解决方案


#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

推荐阅读