Saving Data Produced within R to Disc
It is often convenient to generate numbers within R and then to use them somewhere else (in a spreadsheet, say). Here are 1000 random integers from a negative binomial distribution with mean mu= 1.2 and clumping parameter or aggregation parameter (k) size = 1.0, that I want to save as a single column of 1000 rows in a file called nbnumbers.txt in directory ‘temp’ on the c: drive:
nbnumbers<-rnbinom(1000, size=1, mu=1.2)
There is general point to note here about the number and order of arguments provided to built-in functions like rnbinom. This function can have two of three optional arguments: size, mean (mu) and probability (prob) (see ?rnbinom). R knows that the unlabelled number 1000 refers to the number of numbers required because of its position, first in the list of arguments. If you are prepared to specify the names of the arguments, then the order in which they appear is irrelevant: rnbinom(1000, size=1, mu=1.2) and rnbinom(1000, mu=1.2, size=1) would give the same output. If optional arguments are not labelled, then their order is crucial: so rnbinom(1000, 0.9, 0.6) is different from rnbinom(1000, 0.6, 0.9) because if there are no labels, then the second argument must be size and the third argument must be prob.
To export the numbers I use write like this, specifying that the numbers are to be output in a single column (i.e. with third argument 1 because the default is 5 columns):
write(nbnumbers,"c:\\temp\\nbnumbers.txt",1)
Get The R Book now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.