3

Possible Duplicate:
R: Print list to a text file

ther are two vectors,x1,x2

x1<-1:3
x2<-1:6

i want to write the two vectors into a file named test in the following format

1 2 3
1 2 3 4 5 6

(one vector in one line in the file)

write(file="c:/test",x1)  
write(file="c:/test",x2,append=TRUE,nlines=6)  

is there a simple way to do ?

Community
  • 1
  • 1
Sj Bq
  • 201
  • 3
  • 6

3 Answers3

4

An easier way - both in terms of writing and reading the data - is to use save and load:

##Save both objects to the file
##BTW, you should always use a file extension
save(x1, x2, file="c:/test.RData")

##Loads both objects into your workspace
load("c:/test.RData")
csgillespie
  • 59,189
  • 14
  • 150
  • 185
  • +1, in addition to easier it is also more robust, and in case floats, no loss of precision. And, `save` can handle any R object. – Paul Hiemstra Nov 18 '12 at 10:35
3

This is a way to write all objects to the same file with one command:

lapply(list(x1, x2), function(x) write(x, "c:/test", length(x), TRUE))
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • While a one-liner is convenient, beware that the file is opened and closed twice so this won't scale well. You'll prefer to write to a file connection (see `?file`) when this gets too slow. – flodel Nov 18 '12 at 12:22
1

You could also paste the numbers into a character vector, and use writeLines to dump them to a file connection.

dat = list(vec1, vec2)
dat_write = paste(dat, collapse = " ")
con = file("c:\test", "w")
writeLines(dat_write, con)
close(con)
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • +1 for opening a file connection which can make a big difference. However I don't think the output is what the OP is expecting, see what `as.character(dat)` does. You could use `invisible(lapply(dat, cat, "\n", file = con))` instead. – flodel Nov 18 '12 at 11:56