I have the following function:
library (reshape)
phenotype <- rnorm (100)
data <- matrix(rnorm(1000), nrow = 10, ncol=100)
spearman.p <-
reshape(
melt(
apply(data, 1, function(y){
cor.test(y,phenotype,method="spearman")
}[c("p.value", "estimate")]
)
), timevar="L2", idvar="L1", direction="wide开发者_如何学JAVA"
)
that I would like to know if there is a more efficent way of getting out the p.value and estimate from a "apply"ed cor.test
Can anyone provide some suggestions?
This is the best I can come up with at the moment.
FUN <- function(y) {
test <- cor.test(y,phenotype,method="spearman")
out <- unlist(test[c("p.value", "estimate")])
}
t(apply(data, 1, FUN))
This would be more compact and delivers the p.values from the duplicated data. Is that what you wanted?:
dtt <- do.call(rbind, apply(data, 1, function(y){
cor.test(y,phenotype,method="spearman")
}[c("p.value", "estimate")]
) )
dtt
### p.value estimate
[1,] 0.2305644 0.1208641
[2,] 0.2305644 0.1208641
[3,] 0.2305644 0.1208641
[4,] 0.2305644 0.1208641
[5,] 0.2305644 0.1208641
[6,] 0.2305644 0.1208641
[7,] 0.2305644 0.1208641
[8,] 0.2305644 0.1208641
[9,] 0.2305644 0.1208641
[10,] 0.2305644 0.1208641
Edit: If you are looking for speed and/or the possibility of easily transporting to parallel-oriented platforms then add this to the list of candidates:
pmtx <- matrix(NA, nrow=nrow(data), ncol=2)
for( i in 1:nrow(data) ) {
pmtx[i, 1:2 ] <- unlist(cor.test(data[i, ],
phenotype,
method="spearman")[c("p.value", "estimate")] ) }
pmtx
精彩评论