我想在列居中对齐的位置打印数据框。下面是我尝试过的操作,我认为打印数据框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

最佳答案

问题是,为了使此功能按预期工作,还需要指定“ 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


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

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()),使其长度相等。

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

08-24 13:32