问题
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