本文介绍了R导入文本文件作为数据框列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很长的txt文件,其组织如下:
I have a long txt file organized as follows:
RANGE
P1 H1
P3 H4
P10 H72
P14 H76
;
RANGE
P1 H1
P10 H8
P11 H8
;
...
我想在R中阅读它,以创建一个数据帧列表,其中RANGE和;界定每个内容.因此,每个数据帧应具有两列(P和H)以及不同数量的行.先谢谢您的帮助.
I would like to read it in R creating a list of dataframes, where RANGE and ; delimit the content of each one. Therefore, each dataframe should have two columns (P's and H's) and different number of rows. Thanks in advance for the help.
推荐答案
在通过 readLines
和 split
根据"RANGE"的位置设置元素
We can do this using read.table
after reading it with readLines
and split
ting the elements based on the position of 'RANGE'
lst <- lapply(split(lines, cumsum(lines=="RANGE")),
function(x) read.table(text=x[-c(1, length(x))], header=FALSE, stringsAsFactors=FALSE))
lst
#$`1`
# V1 V2
#1 P1 H1
#2 P3 H4
#3 P10 H72
#4 P14 H76
#$`2`
# V1 V2
#1 P1 H1
#2 P10 H8
#3 P11 H8
数据
lines <- readLines("yourfile.txt")
这篇关于R导入文本文件作为数据框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!