问题是,为了使其按您的预期工作,“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