我对r很新,我似乎找不到解决这个问题的方法。我正在创建具有许多自变量和相同的两组因变量的相关表。我使用从这个网站(http://www.sthda.com/english/wiki/elegant-correlation-table-using-xtable-r-package#combine-matrix-of-correlation-coefficients-and-significance-levels)获得的这个函数的costars函数。输出如下:
| | allo | csub | glumet |
|--------|-----------|-----------|-----------|
| allo | | | |
| csub | 0.57**** | | |
| glumet | 0.58**** | 0.17**** | |
| lipmet | 0.41**** | 0.10** | 0.36**** |
我希望能够获取一个我拥有的数据帧,其中我的因变量沿着一个(x)轴具有它们,并且沿着另一个(y)轴具有变化的自变量列表。看起来像这样:
| | allo | csub | glumet |
|---------|-----------|-----------|-----------|
| A1SEMA | -0.19**** | -0.17**** | 0.11*** |
| A1SEMD | 0.05 | 0.00 | -0.02 |
| A1SMMOD | -0.12**** | -0.11*** | 0.04 |
这是我在上面链接的网站中包含的代码后使用的代码。 (allo是包含我的因变量的数据框之一)
corvar <- select(bio, M2ID, A1SEMA, A1SEMD, A1SMMOD, A1SEFA, A1SEFD, A1SEFMOD, A1SEMAPA)
corvar1 <- left_join(allo, corvar)
corvar1 <- select(corvar1, -1)
var1 <- corstars(corvar1)
然后我将所有内容导出为excel(根据我的顾问的要求)。
如果我不得不猜测我需要更改costars功能的rcorr部分(第7行),但我不知道要将其更改为什么以获得所需的输出。
这是corstarts功能
corstars <-function(x, method=c("pearson", "spearman"),
removeTriangle=c("upper", "lower"),
result=c("none", "html", "latex")){
#Compute correlation matrix
require(Hmisc)
x <- as.matrix(x)
correlation_matrix<-rcorr(x, type=method[1])
R <- correlation_matrix$r # Matrix of correlation coeficients
p <- correlation_matrix$P # Matrix of p-value
## Define notions for significance levels; spacing is important.
mystars <- ifelse(p < .0001, "****", ifelse(p < .001, "*** ", ifelse(p < .01, "** ", ifelse(p < .05, "* ", " "))))
## trunctuate the correlation matrix to two decimal
R <- format(round(cbind(rep(-1.11, ncol(x)), R), 2))[,-1]
## build a new matrix that includes the correlations with their apropriate stars
Rnew <- matrix(paste(R, mystars, sep=""), ncol=ncol(x))
diag(Rnew) <- paste(diag(R), " ", sep="")
rownames(Rnew) <- colnames(x)
colnames(Rnew) <- paste(colnames(x), "", sep="")
## remove upper triangle of correlation matrix
if(removeTriangle[1]=="upper"){
Rnew <- as.matrix(Rnew)
Rnew[upper.tri(Rnew, diag = TRUE)] <- ""
Rnew <- as.data.frame(Rnew)
}
## remove lower triangle of correlation matrix
else if(removeTriangle[1]=="lower"){
Rnew <- as.matrix(Rnew)
Rnew[lower.tri(Rnew, diag = TRUE)] <- ""
Rnew <- as.data.frame(Rnew)
}
## remove last column and return the correlation matrix
Rnew <- cbind(Rnew[1:length(Rnew)-1])
if (result[1]=="none") return(Rnew)
else{
if(result[1]=="html") print(xtable(Rnew), type="html")
else print(xtable(Rnew), type="latex")
}
}
感谢您的帮助!