如何读取标题但也跳过行-read.table()?

如何读取标题但也跳过行-read.table()?

问题描述:

Data.txt:

Index;Time;
1;2345;
2;1423;
3;5123;

代码:

dat <- read.table('data.txt', skip = 1, nrows = 2, header =TRUE, sep =';')

结果:

  X1 X2345
1  2  1423
2  3  5123

我希望标题为索引和时间",如下所示:

I expect the header to be Index and Time, as follows:

  Index Time
1   2   1423
2   3   5123

我该怎么做?

恐怕没有直接的方法可以实现这一目标.您要么读了整个表,然后删除了不需要的行,要么读了两次表,以后再分配标题:

I am afraid, that there is no direct way to achieve this. Either you read the entire table and remove afterwards the lines you don't want or you read in the table twice and assign the header later:

header <- read.table('data.txt', nrows = 1, header = FALSE, sep =';', stringsAsFactors = FALSE)
dat    <- read.table('data.txt', skip = 2, header = FALSE, sep =';')
colnames( dat ) <- unlist(header)