列中心对齐的列打印数据框 [英] Print data frame with columns center-aligned

查看:93
本文介绍了列中心对齐的列打印数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在列居中对齐的情况下打印数据框.下面是我尝试过的操作,我认为打印数据框test1会导致列在中心对齐,但事实并非如此.关于如何执行此操作有任何想法吗?

I would like to print a data frame where the columns are center aligned. Below is what I have I tried, I thought printing the data frame test1 would result in the columns being aligned in the center but this is not the case. Any thoughts on how I can do this?

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

推荐答案

问题是,为使此功能按预期工作,还需要指定"width"自变量.

The problem is that in order for this to work as you expect, the "width" argument needs to also be specified.

这是一个例子:

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  

但是,这种方法如何用于变量名长度不同的列?不太好.

But, how does this approach work with columns where the variable names are different lengths? Not so well.

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             

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

There is, of course, a workaround: change the "width" of each variable name to be equal lengths by padding them with spaces (using 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

这篇关于列中心对齐的列打印数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆