Header to the existing data frame

Dear team, I would like to insert a header to the data frame which is created or coerced from the numeric class. Repex is provided below. After the as.data.frame, there is a lack of the header of the resultant data frame. I hope you will help me in this. Thank you.

cost <- tibble::tribble(
          ~cost_bucket, ~total_cost, ~direct_cost, ~indirect_cost,
                  "vc",        100L,          80L,            20L,
                  "vc",        150L,         100L,            50L,
                  "vc",        200L,         100L,           100L
          )

cost
#> # A tibble: 3 x 4
#>   cost_bucket total_cost direct_cost indirect_cost
#>   <chr>            <int>       <int>         <int>
#> 1 vc                 100          80            20
#> 2 vc                 150         100            50
#> 3 vc                 200         100           100

cost.colsum = colSums(cost[, 2:4])

cost.colsum
#>    total_cost   direct_cost indirect_cost 
#>           450           280           170

class(cost.colsum)
#> [1] "numeric"

cost.colsum.df = as.data.frame(cost.colsum)

class(cost.colsum.df)
#> [1] "data.frame"

cost.colsum.df
#>               cost.colsum
#> total_cost            450
#> direct_cost           280
#> indirect_cost         170

# desired header

desired <- tibble::tribble(
                  ~cost_item, ~cost.colsum,
                "total_cost",         450L,
               "direct_cost",         280L,
             "indirect_cost",         170L
             )
desired
#> # A tibble: 3 x 2
#>   cost_item     cost.colsum
#>   <chr>               <int>
#> 1 total_cost            450
#> 2 direct_cost           280
#> 3 indirect_cost         170

Created on 2024-11-23 with reprex v2.1.1

The rownames_to_column function can get you what you want.

library(tidyverse)
cost <- tibble::tribble(
  ~cost_bucket, ~total_cost, ~direct_cost, ~indirect_cost,
  "vc",        100L,          80L,            20L,
  "vc",        150L,         100L,            50L,
  "vc",        200L,         100L,           100L
)

cost.colsum = colSums(cost[, 2:4])
cost.colsum.df = as.data.frame(cost.colsum)
cost.colsum.df <- rownames_to_column(cost.colsum.df, var = "cost_item")
cost.colsum.df
#>       cost_item cost.colsum
#> 1    total_cost         450
#> 2   direct_cost         280
#> 3 indirect_cost         170

Created on 2024-11-22 with reprex v2.1.1

1 Like

@FJCC Thank you so much for your prompt response in the weekend. Appreciated.