Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 799
user1471980 Avatar asked Apr 27 '15 14:04

user1471980


People also ask

What does readLines return in R?

The readLines function accepts a URL or file as its first argument, and it returns a vector with as many elements as there are lines from the input source. Unlike scan or read. table, readLines simply extracts the text from its input source and returns each line as a character string.

How does the readLines function work?

The readLines function reads text lines from an input file. The n. readLines function of the reader package provides additional functionalities for reading lines, such as skipping ahead in a file or ignoring comments and headers. The readline function interactively reads a line from the terminal.


1 Answers

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)
}
like image 177
paul_dg Avatar answered Oct 21 '22 08:10

paul_dg