我有一个名为“d”、“n”、“beta”、“family”、“alpha”和“value”的data.frame。我想创建一个带有 的 LaTeX 表Hmisc::latex
,其中前三列包含变量“d”、“n”和“beta”,它们给出了相应的行名。其他变量(“family”、“alpha”)应显示在剩余的列中(“F1”和“F2”中的每一个——family 的元素——定义一个组;对于这两个组中的每一个,不同的alpha 的值定义列;总体而言,因此有 2 * 3 = 6 列包含相应的“值”)。这是我到目前为止所拥有的:
## running parameters
nn <- length(n <- c(100, 500)) # sample sizes
nd <- length(d <- c(10, 100, 1000)) # dimensions
nfamily <- length(family <- c("F1", "F2")) # families
nbeta <- length(beta <- c(0.25, 0.75)) # betas
nalpha <- length(alpha <- c(0.95, 0.99, 0.999)) # alphas
## create array containing the results
res <- array(NA, dim=c(nn, nd, nfamily, nbeta, nalpha),
dimnames=list(n=n, d=d, family=family, beta=beta, alpha=alpha))
set.seed(1)
for(i in 1:nn){
for(j in 1:nd){
for(k in 1:nfamily){
for(l in 1:nbeta){
for(m in 1:nalpha){
res[i,j,k,l,m] <- i+j+k+l+m+runif(1) # some dummy values
}
}
}
}
}
## create a data.frame from the array of values
df <- as.data.frame.table(res, responseName="value")
## sort it according to the variables you want to display in the rows and bring the
## corresponding columns to the front/beginning
row.vars <- c("d", "n", "beta") # specify row variables
df. <- df[with(df, do.call(order, sapply(row.vars, as.name))), # sort rows
c(row.vars, setdiff(names(df), row.vars))] # sort colums
## format numbers, set unwanted row names to NA
df.. <- df.
df..$value <- formatC(df.$value, digits=3, format="f")
names2NA <- function(x) {x[c(FALSE, x[-1]==x[-length(x)])] <- NA; x} # arg = TRUE <=> entry equal to previous one
for(j in 1:length(row.vars)) df..[, row.vars[j]] <- names2NA(df..[, row.vars[j]])
## now use Hmisc's latex()
require(Hmisc)
latex(df.., title="title",
file="",
label="tab:res",
cgroup=c("family", "alpha"),
na.blank=TRUE, # use blanks rather than NA => not working (see first columns)!
rowname=NULL,
colheads=c("Family", "alpha"), # character() specifying column headings
dcolumn=TRUE,
booktabs=TRUE,
caption="My table containing all results.",
caption.loc="bottom",
collabel.just=rep("c", 2),
where="htbp",
center="centering",
type="verbatim",
helvetica=FALSE
)
以下是我的问题:
1)为什么前三列中的 NA 没有被空格替换(应该是这种情况na.blank=TRUE
)?
2) 为什么要插入一个空的第四列?
3) 如何在上述列中获取变量“family”和“alpha”作为组?
更新
同时,我设法将 data.frame 转换为矩阵。我有类似的问题,我在这里发布(因为它更具体):Hmisc:如何使用latex()对列变量进行分组?