【问题标题】:Column names shift to left on read.table or read.csv列名在 read.table 或 read.csv 上向左移动
【发布时间】:2016-09-15 02:48:49
【问题描述】:

最初我有这个 TSV 文件(示例):

name   type   qty   
cxfm   1C     0
d2     H50    2
g3g    1G     2
hb     E37    1
nlx    E45    4

所以我使用 read.csv 从 .tsv 文件中读取数据,但我总是得到这个输出:

name   type   qty   
1      cxfm   1C     0
2      d2     H50    2
3      g3g    1G     2
4      hb     E37    1
5      nlx    E45    4

而不是得到这个:

       name   type   qty   
1      cxfm   1C     0
2      d2     H50    2
3      g3g    1G     2
4      hb     E37    1
5      nlx    E45    4

有什么想法吗?这是我用来读取文件的:

    file_list<-list.files()

for (file in file_list){

  if (!exists("dataset")){
    dataset <- read.table(file, header = TRUE, sep = "\t", row.names = NULL, blank.lines.skip = TRUE, fill = TRUE)
    names(dataset) <- c("rowID", names(dataset)[1:ncol(dataset)-1])
    }

  if (exists("dataset")){
    temp_dataset <- read.table(file, header = TRUE, sep = "\t", row.names = NULL, blank.lines.skip = TRUE, fill = TRUE)
    names(temp_dataset) <- c("rowID", names(temp_dataset)[1:ncol(temp_dataset)-1])
    dataset <- rbind(dataset, temp_dataset)
    rm(temp_dataset)
  }

}

dataset <- unique(dataset)

write.table(dataset, file = "dataset.tsv", sep = "\t")

【问题讨论】:

  • 你试过row.names=False吗?
  • @Erin 我想建议这个,但也许他想保留行名。
  • 哦,对了!实际上我认为 row.names=1 可能会奏效。这将告诉 R 标题的第一个元素对应于 csv 中的第二列...
  • 我放 row.names = NULL 因为我的第一列中有重复值(以避免出现此错误:duplicate 'row.names' are not allowed

标签: r data-analysis read.table read.csv


【解决方案1】:

您的 CSV 源文件中似乎缺少列标题。这里的一种选择是保留您的 read.csv() 调用,并简单地调整生成的数据框的名称:

df <- read.csv(file,
               header = TRUE,
               sep = "\t",
               row.names = NULL,
               blank.lines.skip = TRUE,
               fill = TRUE,
               comment.char = "",
               quote = "", stringsAsFactors = FALSE)

names(df) <- c("rowID", names(df)[1:ncol(df)-1])

【讨论】:

  • 我这样做了,现在我有这个错误Error in names(dataset) &lt;- c("rowID", names(dataset)) : 'names' attribute [13] must be the same length as the vector [12]
  • 对不起,使用这个:names(df) &lt;- c("rowID", names(df)[1:ncol(df)-1])
  • 非常感谢,但现在我有这个 `match.names(clabs, names(xi)) 中的错误:名称与以前的名称不匹配`
  • 那么您的 R 脚本中一定还有其他问题。如果您发布相关代码,我可能会提供帮助。
  • 将此代码放在您的问题中,而不是作为评论。从文件中读取每个dataset 数据帧后,您打算如何处理它?这段代码 sn-p 表明你正在覆盖每一个,这对我来说没有太大意义。
【解决方案2】:

这是我必须做的修复它:将 row.names 设置为 FALSE

write.table(dataset, file = "data.tsv", sep = "\t", row.names = FALSE)

【讨论】:

  • 这是对原始问题的直接回答。
猜你喜欢
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多