向数据框添加其他标题

时间:2019-03-11 22:02:41

标签: 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会导致错误。行数保持不变(未创建新行)。感谢您的提示!

1 个答案:

答案 0 :(得分:1)

#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