uv wrote:> Hi. I have a text file containing a few hundred lines of numbers, each line
> has a different length. For example:
>
> 1 4 1 1 7
> 3 11 1 1 1 1 1 1 2
> 2 4 1 2
>
> And so on. I need to do a simple plot function for each line, and then to
> save each plot into a separate file. Is there any way doing it from within
> R?
You can use read.table with the fill argument:
> read.table("file.txt",fill=NA)
V1 V2 V3 V4 V5 V6 V7 V8 V9
1 1 4 1 1 7 NA NA NA NA
2 3 11 1 1 1 1 1 1 2
3 2 4 1 2 NA NA NA NA NA
and then loop over rows. You may have to tell read.table the maximum
number of columns in your data, since it only looks at the first five
rows to have a guess at the size.
Or you can use readLines("file.txt") to read each line into an
element
of a character vector, then use strsplit() to break it up:
> lapply(readLines("file.txt"),
function(s){
as.numeric(unlist(strsplit(s,split=" ")))
})
[probably a neater way to do this but I'm not in the mood for playing R
golf today]
which gives a list:
[[1]]
[1] 1 4 1 1 7
[[2]]
[1] 3 11 1 1 1 1 1 1 2
[[3]]
[1] 2 4 1 2
You could then lapply() on this list to do whatever to the elements,
in your case the plotting.
Barry