Creating a new header and making existing columns into headers

Hi everyone,

I've converted a table to something that is data frame-ish, but the structure is a tad wonky. The structure can be seen via dput below:

structure(c(39L, 50L, 1L, 1L, 0L, 298L, 167L, 440L, 220L, 146L, 
347L, 704L, 1390L, 1743L, 2050L, 3077L, 4862L, 2700L, 7994L, 
8049L, 8873L, 10265L, 10351L, 9377L, 8919L, 8902L, 4546L, 8L, 
7L, 0L, 0L, 0L, 32L, 12L, 19L, 19L, 99L, 134L, 206L, 254L, 345L, 
323L, 399L, 485L, 271L), dim = c(9L, 5L), dimnames = structure(list(
    c("2013", "2014", "2015", "2016", "2017", "2018", "2019", 
    "2020", "2021"), c("c", "C", "NO VALUE", "p", "P")), names = c("", 
"")), class = "table")

When I run this, the first row consists of : [nothing], c, C, NO VALUE, p, and P. Under the column without a header is [nothing], and under the rest are numbers. What I'd like to do is add a column header that says "year" to where there is currently nothing, and then make the first row of the remaining 5 columns into headers.

Is it possible to do this easily?

Thanks!

library(tidyverse)

a <- structure(c(39L, 50L, 1L, 1L, 0L, 298L, 167L, 440L, 220L, 146L, 
            347L, 704L, 1390L, 1743L, 2050L, 3077L, 4862L, 2700L, 7994L, 
            8049L, 8873L, 10265L, 10351L, 9377L, 8919L, 8902L, 4546L, 8L, 
            7L, 0L, 0L, 0L, 32L, 12L, 19L, 19L, 99L, 134L, 206L, 254L, 345L, 
            323L, 399L, 485L, 271L), dim = c(9L, 5L), dimnames = structure(list(
              c("2013", "2014", "2015", "2016", "2017", "2018", "2019", 
                "2020", "2021"), c("c", "C", "NO VALUE", "p", "P")), names = c("", 
                                                                               "")), class = "table")


b <- as.data.frame.matrix(a) %>% 
  as_tibble(rownames = "year")


> b
# A tibble: 9 × 6
  year      c     C `NO VALUE`     p     P
  <chr> <int> <int>      <int> <int> <int>
1 2013     39   146       7994     8    99
2 2014     50   347       8049     7   134
3 2015      1   704       8873     0   206
4 2016      1  1390      10265     0   254
5 2017      0  1743      10351     0   345
6 2018    298  2050       9377    32   323
7 2019    167  3077       8919    12   399
8 2020    440  4862       8902    19   485
9 2021    220  2700       4546    19   271
1 Like

Much grief comes from using a data frame to make a presentation table. Use a tool like {gt} to separate the tasks.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.