从一行读取多个记录

时间:2020-12-25 08:21:35

I want to read data from a file which has the data in form of a key value pair, spread over multiple lines. Please help me read this data into a data.frame.

我想从一个文件中读取数据,该文件具有键值对形式的数据,分布在多行上。请帮我把这些数据读入data.frame。

Data :

数据:

1:0.344 2:0.0234 3:.6723 5:0.265 9:0245 15:0.309 

And so on the data spans across multiple lines,

等数据跨越多行,

I want the data in the form :

我想要表格中的数据:

 key  value
  1   0.344 
  2  0.0234 
  3   .6723
  5   0.265 
  9    0245 
  15  0.309 

1 个解决方案

#1


1  

You can read the file with readLines and use strsplit to split by space and :, then convert to a two column matrix and wrap it with as.data.frame

您可以使用readLines读取该文件,并使用strsplit按空格和:拆分,然后转换为两列矩阵并使用as.data.frame包装它

 v1 <- readLines('multiline.txt')
 m1 <- matrix(as.numeric(strsplit(v1, '[: ]')[[1]]), ncol=2,
         byrow=TRUE, dimnames=list(NULL, c('key', 'value')))
 d1 <- as.data.frame(m1)
 head(d1,3)
 #  key  value
 #1   1 0.3440
 #2   2 0.0234
 #3   3 0.6723

#1


1  

You can read the file with readLines and use strsplit to split by space and :, then convert to a two column matrix and wrap it with as.data.frame

您可以使用readLines读取该文件,并使用strsplit按空格和:拆分,然后转换为两列矩阵并使用as.data.frame包装它

 v1 <- readLines('multiline.txt')
 m1 <- matrix(as.numeric(strsplit(v1, '[: ]')[[1]]), ncol=2,
         byrow=TRUE, dimnames=list(NULL, c('key', 'value')))
 d1 <- as.data.frame(m1)
 head(d1,3)
 #  key  value
 #1   1 0.3440
 #2   2 0.0234
 #3   3 0.6723