当数据行在行尾包含额外的分隔符时,如何读取R中的制表符分隔文件?

时间:2015-06-01 07:32:09

标签: r

我正在尝试读取文件,但它有一个恼人的问题。标题有5列,但由于数据行末尾有一个额外的制表符,数据有6列。它混淆了R,因此它将项目代码作为行名称,并且所有数据都不会移动一个位置。

> items <- read.csv("http://download.bls.gov/pub/time.series/cu/cu.item", sep = "\t")
> items[1,]
               item_code item_name display_level selectable sort_sequence
AA0 All items - old base         0          TRUE          2            NA
> row.names(items[1,])
[1] "AA0"

知道怎么解决这个问题吗?如果我指定row.names = NULL,它会将项目代码读入“row.names”列,但所有内容仍然会被移动。

> items <- read.csv("http://download.bls.gov/pub/time.series/cu/cu.item", sep = "\t", row.names = NULL)
> items[1,]
  row.names            item_code item_name display_level selectable sort_sequence
1       AA0 All items - old base         0          TRUE          2            NA

1 个答案:

答案 0 :(得分:2)

正如我的评论所述,您可以尝试在没有第一行的情况下读取文件,然后在稍后添加标题。

类似的东西:

read.table("http://download.bls.gov/pub/time.series/cu/cu.item", 
           header = FALSE, skip = 1, 
           col.names = c(
             scan("http://download.bls.gov/pub/time.series/cu/cu.item", 
                  what = "", n = 5), "XXXXX"), 
           sep = "\t")[-6]

[-6]将删除NA值列。

以上是我得到的内容:

head(
  read.table("http://download.bls.gov/pub/time.series/cu/cu.item", 
             header = FALSE, skip = 1, 
             col.names = c(
               scan("http://download.bls.gov/pub/time.series/cu/cu.item", 
                    what = "", n = 5), "XXXXX"), 
             sep = "\t")[-6])
# Read 5 items
#   item_code                                          item_name display_level
# 1       AA0                               All items - old base             0
# 2      AA0R Purchasing power of the consumer dollar - old base             0
# 3       SA0                                          All items             0
# 4      SA0E                                             Energy             1
# 5     SA0L1                                All items less food             1
# 6    SA0L12                    All items less food and shelter             1
#   selectable sort_sequence
# 1       TRUE             2
# 2       TRUE           399
# 3       TRUE             1
# 4       TRUE           374
# 5       TRUE           358
# 6       TRUE           361