Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 打印数据框,使列居中对齐_R_Printing_Dataframe_Formatting_Center Align - Fatal编程技术网

R 打印数据框,使列居中对齐

R 打印数据框,使列居中对齐,r,printing,dataframe,formatting,center-align,R,Printing,Dataframe,Formatting,Center Align,我想打印一个列居中对齐的数据框。下面是我尝试过的,我认为打印数据框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(t

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

调用此函数以获得如下显示的数据帧:

def pd_centered(df):
    return df.style.set_table_styles([
        {"selector": "th", "props": [("text-align", "center")]},
        {"selector": "td", "props": [("text-align", "center")]}])
e、 g:

这将使标题和实际数据单元格居中对齐,您可以移除
td
th
以禁用其中一个


资料来源:

你是说圆柱的中心吗?所以1,2,3在
变量1
中的
a
(大致)下排列?@Tylerlinker是的,这就是我的意思。@Glen,你的问题解决得够充分了吗?如果没有,请添加评论,以便您的问题可以进一步研究。@mrdwab回答得很好,谢谢。我正要弹出
sprintf
+1
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
def pd_centered(df):
    return df.style.set_table_styles([
        {"selector": "th", "props": [("text-align", "center")]},
        {"selector": "td", "props": [("text-align", "center")]}])
display(pd_centered(original_df))