【问题标题】:Add Additional Headers to a Dataframe向数据框添加其他标头
【发布时间】:2019-03-11 22:02:40
【问题描述】:

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

【问题讨论】:

  • “使用 cbind 会导致错误,因为名称不匹配” 听起来更像 rbind,你是这个意思吗?我可能把事情搞混了......
  • 您是否要使用修改后的数据创建一个新的csv 并将标题行添加回其中?
  • 我的意思是 rbind。感谢您的指正。已更新。
  • 是的,我想创建一个新的 csv,其中包含原始的三个标题行(但包含更新的变量)

标签: r


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 2019-04-04
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多