[R] how to calculate a table

Dieter Menne dieter.menne at menne-biomed.de
Mon Apr 12 09:13:30 CEST 2010



Bernd Dittmann wrote:
> 
> (Sample boot code see below)
> ...
> So far so good. But how can I bring it into table-form whereby the
> combination of all 10 different weights (setting steps as 1) and their
> respective bootstrapped means are printed:
> 
> weights		mean.boot
> 1		....
> 2		....
> ...		....
> 10		....
> 
> 

Divide et impera.

Dieter

x <- rnorm(100, mean=100, sd=4)
y <- rnorm(100, mean=120, sd=10)

# Step 1: use a variables instead of  constants
n1 = 8
maxn = 10
portfolio <- c(rep(x, n1), rep(y, maxn-n1))
mean.boot <- function(z){
  mean(sapply(lapply(1:20, function(i)sample(z, replace=F, size=30)),mean))}
mean.boot(portfolio)


# Step 2 : Wrap it in a function and test it
meanBoot <- function(n1) {
  portfolio <- c(rep(x, n1), rep(y, 10-n1))
  mean.boot <- function(z){
    mean(sapply(lapply(1:20, function(i)sample(z, replace=F,
size=30)),mean))}
  mean.boot(portfolio)
}
# Test it
meanBoot(8)

# Step 3: The c-programmer's way
res = data.frame()
n1s =  1:(maxn-1)
for (n1 in n1s) {
  res <- rbind(res,data.frame(n1 = n1, mean =meanBoot(n1)))
}  
res


# Room for improvement here: use one of the Xapply functions here, or 
# pre-allocate res if you have many data
lapply(n1s, meanBoot)
# ugly output, let's simplify
sapply(n1s, meanBoot)
# looks better, decorate it!
data.frame(n= n1s, mean=sapply(n1s, meanBoot))

-- 
View this message in context: http://n4.nabble.com/how-to-calculate-a-table-tp1836676p1836743.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list