I have a data-frame in R that looks like this.
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)
I'm trying to merge the column headers - Housing$Housing
& Housing$Values
into a Single cell called Housing_characteristics
and the rest of the data frame must be the same. Exactly like an Excel spreadsheet.
https://i.stack.imgur.com/J7AjF.jpg
I want the output to look something like this - https://i.stack.imgur.com/qHd0C.jpg
I have a bunch of these data-frames that I'm displaying in an RShiny application and need to format the headers for a clean look.
Thanks!
This might be the closest thing you can get:
library(stargazer)
stargazer(Housing, summary = FALSE, type = "text",
rownames = FALSE, align = TRUE, title = "Housing Characteristics")
Text Table:
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%
-----------------------------------
Note that this is not a data.frame
. This is a table in text form outputted into your console, so you cannot manipulate it like a data.frame
.
If you are fine with latex tables in your shiny app, you can also use the type = latex
option, which is the default:
library(stargazer)
stargazer(Housing, summary = FALSE, header = FALSE,
title = "Housing Characteristics")
Latex Code:
\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}
This would look quite nice on a shiny app!
Modify the displayed output and not the data.frame
. The following will draw an interactive table with title and still allow columns to be sorted:
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)
example derived from section 2.5 of http://rstudio.github.io/DT/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.