【问题标题】:Flat file read- line to columns R平面文件读取行到列 R
【发布时间】:2018-10-21 19:33:10
【问题描述】:

我有一个包含以下数据的 .txt 文件:

PSAP_Agency

Public Safety 

Char(120)    

PSAP_ID      

Pitney Bowes 

Integer       

我需要在 R 中阅读这个结构:

column      desc           type
PSAP_Agency Public Safety  Char(120)
PSAP_ID     Pitney Bowes   Integer

我该怎么做?

【问题讨论】:

  • PSAP_ID 是否总是一位整数?如果是这样,您可以使用read.fwf(filename, widths = c(120, 1))

标签: r flat-file


【解决方案1】:

考虑到您的文本文件包含 3 行序列中的数据,它们之间有空行:

PSAP_Agency

Public Safety 

Char(120)    

PSAP_ID      

Pitney Bowes 

Integer    

以下代码从文件中读取数据并将其转换为所需的数据帧结构:

text_file_name <- "text.txt" #path to the text file
number_of_columns <- 3
txt <- readLines(text_file_name)
txt <- txt[txt != ""] #removing empty lines
lst <- split(txt, as.integer(gl(length(txt), number_of_columns, length(txt))))
df <- as.data.frame(do.call(rbind, lst))
names(df) <- c("column", "desc", "type")
print(df)

希望对您有所帮助! :)

【讨论】:

  • 是的!谢谢 !! :)
猜你喜欢
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多