简体   繁体   中英

how do you convert output from readLines to data frame in 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?

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)
}

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)
}

If your original file is csv, once you readlines..

x=readLines("file.csv")

You can use read.csv

Df=read.csv (x)

Or if rather want a data.table you can use

Df=fread (x, sep=",")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM