R read.table(),我怎样才能读取标题,但也跳过行? [英] R read.table(), how can I read the header but also skip lines?

查看:284
本文介绍了R read.table(),我怎样才能读取标题,但也跳过行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Data.txt:

 索引;时间; 
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

我希望标题是Index和Time,如下:

 索引时间
1 2 1423
2 3 5123

我该如何做?

解决方案

<恐怕没有直接的办法可以做到这一点。您可以读整个表格,然后删除不需要的行,或者您在表格中读取两次并稍后分配标题:

  header<  -  read.table('data.txt',nrows = 1,header = FALSE,sep =';',stringsAsFactors = FALSE)
dat< - read.table('data。
colnames(dat)< - unlist(header)
< $ code>< / pre>

Data.txt:

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

The code:

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

The result:

  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

How do I do that?

解决方案

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)

这篇关于R read.table(),我怎样才能读取标题,但也跳过行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆