In the cmprsk
package one of the tests to call crr
shows the following:
crr(ftime,fstatus,cov,cbind(cov[,1],cov[,1]),function(Uft) cbind(Uft,Uft^2))
It's the final inline function function(Uft) cbind(Uft,Uft^2)
which I am interested in generalizing. This example call to crr
above has cov1
as cov
and cov2
as cbind(cov[,1],cov[,1])
, essentially hardcoding the number of covariates. Hence the hardcoding of the function function(Uft) cbind(Uft,Uft^2)
is sufficient.
I am working on some benchmarking code where I would like the number of covariates to be variable. So I generate a matrix cov2
which is has nobs
rows and ncovs
columns (rather than ncovs
being pre-defined as 2 above).
My question is - how do I modify the inline function function(Uft) cbind(Uft,Uft^2)
to take in a single column vector of length nobs
and return a matrix of size nobs x ncovs
where each column is simply the input vector raised to the column index?
Minimal reproducible example below. My call to z2 <- crr(...)
is incorrect:
#!/usr/bin/env Rscript
library(cmprsk)
for(seed in c(1, 2)) {
for(Nobs in c(10, 20)) {
for(Ncovs in c(2, 3)) {
set.seed(seed);
ftime <- rexp(Nobs);
fstatus <- sample(0:Ncovs,Nobs,replace=TRUE);
cov1 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
cov2 <- matrix(runif(Nobs*Ncovs),nrow=Nobs);
df <- data.frame(ftime=ftime, fstatus=fstatus, cov1=cov1);
z1 <- crr(ftime, fstatus, cov1, );
z2 <- crr(ftime, fstatus, cov1, cov2, function(Uft) Uft^cbind(1:Ncovs));
}
}
}
CodePudding user response:
You can use sapply
:
Uft <- 1:5
Ncovs <- 6
sapply(1:Ncovs, function(i) Uft^i)
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1 1 1 1 1 1
#> [2,] 2 4 8 16 32 64
#> [3,] 3 9 27 81 243 729
#> [4,] 4 16 64 256 1024 4096
#> [5,] 5 25 125 625 3125 15625
In your code :
function(Uft) sapply(1:Ncovs, function(i) Uft^i)
A better alternative using outer
:
function(Uft) outer(Uft, 1:Ncovs, "^")
CodePudding user response:
vec <- 1:4
ncovs <- 5
matrix(unlist(Reduce("*", rep(list(vec), ncovs), accumulate= TRUE)), ncol = ncovs)
gives:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 4 8 16 32
[3,] 3 9 27 81 243
[4,] 4 16 64 256 1024