将具有可变列数的文本文件读取到列表 [英] Read a text file with variable number of columns to a list

查看:67
本文介绍了将具有可变列数的文本文件读取到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的文件:

I have a file like this:

mylist.txt
234984  10354  41175 932711 426928
1693237   13462

此文件的每一行具有不同数量的元素,每行最少1个元素. 我想将其读入这样的列表中:

Each line of this file has different number of elements, minimum of 1 element per line. I would like to read it into a list like this:

> print(head(mylist,2))
[[1]]
[1] 234984  10354  41175 932711 426928

[[2]]
[1] 1693237   13462

推荐答案

假定空格是定界符:

fc <- file("mylist.txt")
mylist <- strsplit(readLines(fc), " ")
close(fc)

如果值由多个空格定界(一个/或不一致的方式),则可以将定界符与正则表达式匹配:

If the values are delimited by several spaces (an/or in unconsistent way), you can match delimiter with regular expression:

mylist.txt
234984   10354   41175 932711      426928
1693237               13462

fc <- file("mylist.txt")
mylist <- strsplit(readLines(fc), " +")
close(fc)

编辑#2

由于strsplit返回字符串,因此您需要将数据转换为数字(这很简单):

And since strsplit returns strings, you need to convert your data to numeric (that's an easy one):

mylist <- lapply(mylist, as.numeric)

这篇关于将具有可变列数的文本文件读取到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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