how do you convert output from readLines to data frame in R

情到浓时终转凉″ 提交于 2021-02-20 16:03:27

问题


I have a txt file that has multiple lines. Each line as text that is separated by space. Number of columns in each line may be different. I need to read each line one at a time, put it into data frame and print it.

I tried this:

x<-readLines("output.txt")


for (i in 2:length(x) ) {
  data<-data.frame(x[[i]])
  print(data)
}

I have to start from line number 2 becasuse line number 1 has some heading info that I dont need.

For example, this prints out something like this:

x[[2]]
[1] "                              dcserver        AIX      2254438400       587317248   026.05   93752=100.00  HDS93752_VMAX1561_RAID1=100.00 "

when I do this:

data<-data.frame(x[[2]])

I get this:

dput(data)

structure(list(x..2.. = structure(1L, .Label = "                              dcserver        AIX      2254438400       587317248   026.05   93752=100.00  HDS93752_VMAX1561_RAID1=100.00 ", class = "factor")), .Names = "x..2..", row.names = c(NA, 
-1L), class = "data.frame")

It looks like I have one row and one column, I need to have 7 columns, like below:

dcserver        AIX      2254438400       587317248   026.05   93752=100.00  HDS93752_VMAX1561_RAID1=100.00

Any ideas?


回答1:


You can use the functions: textConnection and read.table.

x<-readLines("output.txt")

for (i in 2:length(x) ) {
  data<-read.table(textConnection(x[[i]]))
  print(data)
}



回答2:


I am sure there are better ways but I have tried this and it works for me:

x<-readLines("output1.txt")

for (i in 2:length(x) ) {
  x<-data.frame(x[[i]])
  writeLines(x[[i]],"test.csv")
  data<-read.csv("test.csv", header=F, sep=" ")
  df<-data[,colSums(is.na(data)) == 0]
  print(df)
}


来源:https://stackoverflow.com/questions/29899155/how-do-you-convert-output-from-readlines-to-data-frame-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!