打印数据框,列中心对齐

Gle*_*len 4 printing formatting r center-align dataframe

我想打印一个数据框,其中列是居中对齐的.下面是我尝试的内容,我认为打印数据框test1会导致列在中心对齐,但事实并非如此.有关如何做到这一点的任何想法?

test=data.frame(x=c(1,2,3),y=c(5,6,7))
names(test)=c('Variable 1','Variable 2')
test[,1]=as.character(test[,1])
test[,2]=as.character(test[,2])
test1=format(test,justify='centre')
print(test,row.names=FALSE,quote=FALSE)
 Variable 1 Variable 2
          1          5
          2          6
          3          7
print(test1,row.names=FALSE,quote=FALSE)
 Variable 1 Variable 2
          1          5
          2          6
          3          7
Run Code Online (Sandbox Code Playgroud)

A5C*_*2T1 9

问题是,为了使其按预期工作width,还需要指定" "参数.

这是一个例子:

test.1 <- data.frame(Variable.1 = as.character(c(1,2,3)), 
                     Variable.2 = as.character(c(5,6,7)))

# Identify the width of the widest column by column name
name.width <- max(sapply(names(test.1), nchar))
format(test.1, width = name.width, justify = "centre")
#   Variable.1 Variable.2
# 1     1          5     
# 2     2          6     
# 3     3          7  
Run Code Online (Sandbox Code Playgroud)

但是,这种方法如何与变量名称长度不同的列一起使用?不太好.

test.2 <- data.frame(A.Really.Long.Variable.Name = as.character(c(1,2,3)), 
                     Short.Name = as.character(c(5,6,7)))

name.width <- max(sapply(names(test.2), nchar))
format(test.2, width = name.width, justify = "centre")
#   A.Really.Long.Variable.Name                  Short.Name
# 1              1                           5             
# 2              2                           6             
# 3              3                           7             
Run Code Online (Sandbox Code Playgroud)

当然,有一种解决方法:通过用空格填充每个变量名称的"宽度"来使其长度相等(使用format())

orig.names <- names(test.2) # in case you want to restore the original names
names(test.2) <- format(names(test.2), width = name.width, justify = "centre")
format(test.2, width = name.width, justify = "centre")
#   A.Really.Long.Variable.Name         Short.Name         
# 1              1                           5             
# 2              2                           6             
# 3              3                           7
Run Code Online (Sandbox Code Playgroud)