tags:

views:

99

answers:

3

I have in R a list like this:

> print(head(mylist,2))
[[1]]
[1] 234984  10354  41175 932711 426928

[[2]]
[1] 1693237   13462

Each element of the list has different number of its elements.

I would like to print this list to a text file like this:

mylist.txt
234984  10354  41175 932711 426928
1693237   13462

I know that I can use sink(), but it prints names of elements [[x]], [y] and I want to avoid it. Also because of different number of elements in each element of the list it is not possible to use write() or write.table().

+5  A: 

Not tested, but it should work (edited after comments)

lapply(mylist, write, "test.txt", append=TRUE, ncolumns=1000)
nico
Tested. Work. You could also use shorthand: `lapply(mylist, write, "test2.txt", append=TRUE)`
Marek
@Marek: Good! I didn't remember you could pass parameters to lapply like that!
nico
Just one important detail, you need to specify ncolumns parameter of write function, otherwise lines will be trimmed to 5 columns only:`lapply(mylist, write, "test3.txt", append=T, ncolumns=1000 )`
pms
Pls edit/add ncolumns to your answer and I will choose it as accepted answer! Shorthand is preferred :)
pms
@pms: edited :)
nico
Actually `write` is modified `cat` (see code) so alternative could be `lapply(mylist, cat, "\n", file="test.txt", append=TRUE)`.
Marek
+1  A: 

Another way

writeLines(unlist(lapply(mylist, paste, collapse=" ")))
Marek
A: 

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);
Carl