read.table或read.csv时列名向左偏移

4

最初我有这个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
@Erin,我想过建议这个,但也许他想保留行名。 - Tim Biegeleisen
哦,对了!实际上我认为row.names=1可能会奏效。这将告诉R,标题的第一个元素对应于csv中的第二列... - Erin
我将row.names = NULL放置在代码中,因为我的第一列存在重复值(为了避免出现错误:不允许重复的'row.names')。 - Chayma Atallah
2个回答

3

您的源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) <- c("rowID", names(dataset)) : 'names' attribute [13] must be the same length as the vector [12] - Chayma Atallah
将此代码放在您的问题中,而不是作为评论。读取每个“数据集”数据框后,您计划做什么?此代码片段显示您正在覆盖每个数据集,这对我来说没有太多意义。 - Tim Biegeleisen
你的代码看起来还不错。你确定每个文件中的列标题都是相同的吗? - Tim Biegeleisen
是的,它们是相同的列标题,受所有文件影响,只是数据每次达到一定行数时就会分成文件。 - Chayma Atallah
这里有一个快速修复方法可以尝试。在第二个if条件中添加names(temp_dataset) <- names(dataset) - Tim Biegeleisen
显示剩余9条评论

2
这是我需要做的来解决它的方法:将 row.names 设置为 FALSE。
write.table(dataset, file = "data.tsv", sep = "\t", row.names = FALSE)

这是对原问题的直接回答。 - WestCoastProjects

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接