如何在r中的数据框中合并列标题

时间:2017-09-22 16:01:16

标签: r excel dataframe

我在R中有一个看起来像这样的数据框。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/cv2.so, 2): Symbol not found: _PyCObject_Type
  Referenced from: /usr/local/lib/python2.7/site-packages/cv2.so
  Expected in: flat namespace
 in /usr/local/lib/python2.7/site-packages/cv2.so

我正在尝试合并列标题 - Housing = c("Average Housing Year Built", "Owner Occupied", "Occupied Units", "Rent as a Percent of MFI", "All Residents", "Hispanic/Latino", "White", "Black", "Asian") Values = c(1920, 5065886, 7255261, 99444.94, "20.54%", "27.7%", "18.67%", "36.64%", "42.42%") Housing = data.frame(Housing, Values) &amp; Housing$Housing进入名为Housing$Values的单个单元格,其余数据框必须相同。完全像Excel电子表格。

https://i.stack.imgur.com/J7AjF.jpg

我希望输出看起来像这样 - https://i.stack.imgur.com/qHd0C.jpg

我有一堆这些数据框,我正在RShiny应用程序中显示,需要格式化标题以获得干净的外观。

谢谢!

2 个答案:

答案 0 :(得分:2)

这可能是你最接近的事情:

library(stargazer)
stargazer(Housing, summary = FALSE, type = "text",
          rownames = FALSE, align = TRUE, title = "Housing Characteristics")

文字表:

Housing Characteristics
===================================
         Housing            Values 
-----------------------------------
Average Housing Year Built   1920  
      Owner Occupied       5065886 
      Occupied Units       7255261 
 Rent as a Percent of MFI  99444.94
      All Residents         20.54% 
     Hispanic/Latino        27.7%  
          White             18.67% 
          Black             36.64% 
          Asian             42.42% 
-----------------------------------

请注意,这是 a data.frame。这是一个输出到您的控制台的文本形式的表格,因此您无法像data.frame那样对其进行操作。

如果你在闪亮的应用程序中使用乳胶表,你也可以使用type = latex选项,这是默认选项:

library(stargazer)
stargazer(Housing, summary = FALSE, header = FALSE,
          title = "Housing Characteristics")

乳胶代码:

\begin{table}[!htbp] \centering 
  \caption{Housing Characteristics} 
  \label{} 
\begin{tabular}{@{\extracolsep{5pt}} cc} 
\\[-1.8ex]\hline 
\hline \\[-1.8ex] 
Housing & Values \\ 
\hline \\[-1.8ex] 
Average Housing Year Built & 1920 \\ 
Owner Occupied & 5065886 \\ 
Occupied Units & 7255261 \\ 
Rent as a Percent of MFI & 99444.94 \\ 
All Residents & 20.54\% \\ 
Hispanic/Latino & 27.7\% \\ 
White & 18.67\% \\ 
Black & 36.64\% \\ 
Asian & 42.42\% \\ 
\hline \\[-1.8ex] 
\end{tabular} 
\end{table}

enter image description here

这在闪亮的应用上看起来相当不错!

答案 1 :(得分:2)

修改显示的输出而不是data.frame。下面将绘制一个带有标题的交互式表格,并且仍然允许对列进行排序:

library(DT)

sketch = htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(colspan = 2, 'Housing Characteristics')
    ),
    tr(
      th('Description'),
      th('Values')
    )
  )
))

datatable(Housing, container = sketch, rownames = FALSE)

enter image description here

示例源自http://rstudio.github.io/DT/

的第2.5节