'How to create a new table in R markdown from an existing table in R shiny
I have a shiny app that outputs the following table:
| France | |
|---|---|
| Population (m) | 67 |
| Size (km) | 543940 |
| No. of cities | 85 |
| Average temperature (summer) | 20 |
| Average temperature (winter) | 5 |
| No. of airports | 464 |
Server code:
shinyServer(function(input, output) {
data <- matrix(c(input$pop, input$size, input$city, temp_sum(a,b),
temp_win(a,b), airport(a), ncol = 1,byrow = T)
colnames(data) <- input$country
rownames(data) <- c("Population (m)", "Size (km)", "No. of cities",
"Average temperature (summer)", "Average temperature (winter)", "No. of
airports")
output$table <- renderTable(data,rownames = TRUE)
I am trying to get this table to display in a report that can be generated from the shiny app using a r markdown file. However I only want the data for the last three rows to be displayed which are based on functions I defined earlier in shiny and I want this in the below format:
| Average temperature (summer) | Average temperature (winter) | No. of airports | |
|---|---|---|---|
| France | 20 | 5 | 464 |
I am unsure how I would do this and would appreciate any help.
Solution 1:[1]
library(tidyverse)
data <- tribble(
~name, ~France,
"population", 67,
"no of cities", 85,
"avg temp summer", 5,
"avg temp winter", 5,
"no airports", 464
)
data %>%
tail(3) %>%
pivot_longer(-name, names_to = "country") %>%
pivot_wider(names_from = name, values_from = value)
#> # A tibble: 1 × 4
#> country `avg temp summer` `avg temp winter` `no airports`
#> <chr> <dbl> <dbl> <dbl>
#> 1 France 5 5 464
Created on 2022-03-09 by the reprex package (v2.0.0)
You might want to use data <- data %>% column_to_rownames("name") before if you do not have a tibble, but just a data.frame.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
