1

Background:

I have a little dataframe composed of percentage estimates across two characteristics. One is "political party", the other is "sex". As it stands, these specific names are unmentioned in the df even if the categories that comprise them are. Here it is:

d <- data.frame(characteristic = c("Republican","Democrat","Male","Female"), 
                percent = c(45, 55, 70, 30),
                stringsAsFactors=FALSE)

For those without R available to them at the moment, here's what that looks like:

what_ive_got

The Problem:

As the result of data analysis, this df is perfectly adequate. But because I want to export it is a .csv file and insert it into a report I'm writing, I'd like to make some aesthetic modifications in order to make that integration as smooth as possible. In particular, I'd like to insert 2 blank rows to act as subheadings. In other words, I'm looking to do something like this:

what_id_like

What I've tried:

I feel I'm quite close, because I can get the new rows in using these two lines of code:

d[nrow(d) + 1,] = c("Party","")
d[nrow(d) + 1,] = c("Sex","")

But that only appends them to the bottom of the dataset and I'm not sure how to move them into the desired positions, or if there a more efficient way to do this.

Thanks for any help!

logjammin
  • 1,121
  • 6
  • 21

2 Answers2

1

You could use add_row:

library(dplyr)
d %>%
        mutate(percent = as.character(percent)) %>%
        add_row(characteristic = "Party", percent = "", .before = 1) %>%
        add_row(characteristic = "Sex", percent = "", .before = 4)

Output:

  characteristic percent
1          Party        
2     Republican      45
3       Democrat      55
4            Sex        
5           Male      70
6         Female      30

Note that the above solution converts percent into a character to match your desired output. If you do not care about replacing "" with NA, then you could do:

d %>%
        add_row(characteristic = "Party", percent = NA, .before = 1) %>%
        add_row(characteristic = "Sex", percent = NA, .before = 4)

Output:

  characteristic percent
1          Party      NA
2     Republican      45
3       Democrat      55
4            Sex      NA
5           Male      70
6         Female      30
bird
  • 2,938
  • 1
  • 6
  • 27
  • This is terrific -- that `.before` argument was exactly the thing I found myself hoping existed. Thanks! – logjammin Jun 04 '21 at 20:02
1

As the OP mentioned, it is aesthestic preference, an option is kableExtra. (Note: This is posted as an alternative way to visualize)

library(kableExtra)
kbl(d) %>%
  kable_paper("striped", full_width = FALSE) %>%
  pack_rows("Party", 1, 3) %>%
  pack_rows("Sex", 3, 4)

-output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662