[R] repeating a function and combining the results
arun
smartpink111 at yahoo.com
Tue Dec 3 06:52:08 CET 2013
HI,
May be this helps:
example <- function(X,n){
lst1 <- list()
for(i in 1:n){
cell1 <- sample(X,1)
cell2 <- sample(X,1)
table1 <- cbind(cell1,cell2)
lst1[[i]] <- table1
}
do.call(rbind,lst1)
}
#or
example1 <- function(X,n){
table1 <- vector()
for(i in 1:n){
cell1 <- sample(X,1)
cell2 <- sample(X,1)
table1 <- rbind(table1,c(cell1=cell1,cell2=cell2))
}
table1
}
set.seed(24)
res1 <- example(1:10,3)
set.seed(24)
res2 <- example1(1:10,3)
identical(res1,res2)
#[1] TRUE
#or
set.seed(24)
res3 <- t(replicate(3,c(sample(10,1),sample(10,1))))
colnames(res3) <- colnames(res2)
identical(res2,res3)
#[1] TRUE
A.K.
I have written a lengthy function that conducts a simulated
mark/recapture study using random numbers. The output from the program
is a matrix with a single row and nine columns (each column contains the results of a different calculation). Because of the random numbers,
each time that I run the program, I get a different result. I need to be able to run it a fixed number of times and have all the results in a
single matrix. I have written a second function that repeats the first
and combines the results into a single table. Each time that I use that
line of code, it reruns the first program, generating a new row of data, and combines it with the previous rows. How do I repeat that line 100
times so that I get a table will 100 rows of data (each row should be
unique).
Here is a simplistic example of what I have so far
example <- function(X){
cell1 <- sample(X,1)
cell2 <- sample(X,1)
table1 <- cbind(cell1,cell2)}
table2 <- example(1:10)
example2 <- function(test){rbind(table2,example(1:10))}
table2 <- example2(table2)
Every time that you enter the line table2 <- example2(table2)
it will add a new line of data to the table, but I don't want to have
to enter that line 100 times. So how do I get that line/function to
repeat a specified number of times?
I have tried both repeat and replicate and neither of them worked.
Thanks for the help
More information about the R-help
mailing list