[R] save txt file

cls59 chuck at sharpsteen.net
Thu Sep 24 01:09:54 CEST 2009



Eiger wrote:
> 
> Hi, I have 2 questions:
> 
> 
> Question 1:
> 
> I define 2  variables: "a", "b":
> 
>> a<-rbinom(4,10,0.8)
> output:
> [1] 9 7 8 8
> 
>> b<-rbinom(2,6,0.7)
> output:
> [1] 4 5
> 
> if I write:
>> write.table(a, file = "filename", etc. etc. .... )
> it save only the values of variable "a".
> 
> There is a way to save in a .txt file the values  "a" and "b" as
> consecutive data?  (but I would use many variables..)
> ..like this:
> 
> 9
> 7
> 8
> 8
> 4
> 5
> 
> Question 2:
> is possible save data as rows?  
> (9 7 8 8 4 5)
> 
> thank's
> 
> Eiger
> 
> 

Assuming you are dealing with vectors of numbers, you can form a "row" of
data using the append function to stick b onto the end of a:

> append( a, b )
[1] 9 7 8 8 4 5

This can be dumped to a file using write.table:

write.table( t( append(a,b) ), 'test.txt', row.names=F, col.names=F,
append=T )

The transpose function t() is used because write.table() assumes a singleton
vector is a column vector and you want row vectors.

If you have two matrices instead of vectors, say:

matA <- matrix( rep(a,4), nrow=4, byrow=T )
matB <- matrix( rep(b,4), nrow=4, byrow=T )

Then you would use the cbind() function instead of the append() function to
form your rows and drop the transpose function:

write.table( cbind(a,b), 'test.txt', row.names=F, col.names=F, append=T )

If you want to overwrite (i.e. start a new file) when you use write.table,
then drop the append=T.

Hope this helps!

-Charlie




-----
Charlie Sharpsteen
Undergraduate
Environmental Resources Engineering
Humboldt State University
-- 
View this message in context: http://www.nabble.com/save-txt-file-tp25531307p25531324.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list