如何实现清洁相关表格输出瓦特/ corstarsl()函数?(How to to achieve c

2019-09-30 18:09发布

有一个很好的相关表函数各地 (唯一一个我知道生产这种特殊的熟悉到那些眼睛)。 贝托尔德已经修改了代码,以达到一个更好的输出。 不过,也有如W,当输出仍然看起来有点搞砸/负相关的情况。

下面我展示了功能第一的小例子如下:

corstarsl <- function(x){
  # corstars1() computes a correlation matrix w/ significance stars
  require(Hmisc)
  x <- as.matrix(x)
  R <- rcorr(x)$r
  p <- rcorr(x)$P

  ## define significance levels
  mystars <- ifelse(p < .001, "***", 
                    ifelse(p < .01, "** ", 
                           ifelse(p < .05, "* ", " ")))

  ## correlation matrix w/ two digits
  R <- format(round(cbind(rep(- 1.11, ncol(x)), R), 2))[, -1]

  ## build a new matrix that includes the correlations w/ appropriate 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
  Rnew <- as.matrix(Rnew)
  Rnew[upper.tri(Rnew, diag = TRUE)] <- ""
  Rnew <- as.data.frame(Rnew)

  ## remove last column and return the matrix (which is now a data frame)
  Rnew <- cbind(Rnew[1:length(Rnew) - 1])
  return(Rnew)
} 

例:

library(MASS)
n <- 100
mymeans <- c(10, 12, 15, 17) # means of each var
Sigma <- matrix(c(1, -.45, .16, -.71,
                  -.45, 1, -.71, .09,
                  .16, -.71, 1, -.17,
                  -.71, .09, -.17, 1), ncol = 4)
dat <- mvrnorm(n = n, mu = mymeans, Sigma, empirical = TRUE)

(cortab <- corstarsl(as.data.frame(dat)))
##          V1       V2     V3
## V1                         
## V2 -0.45***                
## V3    0.16  -0.71***       
## V4 -0.71***    0.09  -0.17 

# or with htmlTable():
library(htmlTable)
htmlTable(cortab, 
      align = paste(rep('l', ncol(cortab)), collapse = ''))

中断输出:

编辑 :随着左对齐我几乎没有,但如何给正面的价值观更多的空间?

预期输出:

有谁知道如何实现函数内部的结果更好的格式(小数点应该对齐)?

Answer 1:

您可以使用tableHTML并使用widths参数来控制列的宽度。 此外,您将需要使用&nbsp; 这是这样一个空间中的HTML字符:

#convert to character
cortab[] <- lapply(cortab, as.character)
#if the cell does not start with a minus add an html space
cortab[] <- lapply(cortab, function(x) {

 ifelse(!startsWith(x, '-'), paste0('&nbsp;', x), x)

})

#convert to html with tableHTML
#control the column widths with the widths argument
library(tableHTML)
tableHTML(cortab, widths = c(40, 60, 60, 60), theme = 'scientific') %>%
 add_css_column(list('text-align', 'left !important'), columns = 1:4)



文章来源: How to to achieve clean correlation table output w/ corstarsl() function?