0

I'm using formattable() from the package formattable in R. Here's some code that produces a table with the issue I want to get around.

a1 <- c(1, 2, 3)
data <- c(100, 155, -4)
a2 <- c(0, paste(data, collapse = "; "), 1000000) 
b <- data.frame(cbind(a1, a2))
                
formattable(b)

Here is the output:

enter image description here

What I want is for the cell with the three entries to have each value on a new line, so it looks like so:

enter image description here

If it looked like this I could remove the semicolons. I made the second image by shrinking my window, but I want the data to always look this way no matter how big the user's window is. Is there a way in formattable() or elsewhere where this can be forced?

Note that I have tried the following in the paste() function and it did not work.

paste(data, collapse = "; \n")
AnthonyH
  • 105
  • 8

2 Answers2

2

I have not used formatable. I wonder if kableExtra is helpful here.

library(knitr)
library(kableExtra)
df <- data.frame(a1 = c(1, 2, 2,2, 3),
                 a2 = c(0, 100, 155, -4, 1000000)) 
kable(df) %>%
  kable_styling(full_width = F) %>%
  collapse_rows(columns = 1:2, valign = "top")

enter image description here

Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27
  • Thanks. It looks pretty good, but the issue comes if in a later column I then want just the three rows again. ``` df <- data.frame(a1 = c(1, 2, 2, 2, 3), a2 = c(0, 100, 155, -4, 1000000), a3 = c(0, 100, 155, -4, 1000000), a4 = c(1,6,6,6,3)) ``` If you run this df through the kable code, the 4th column is 1,6,6,6,3 instead of just 1,6,3. – AnthonyH Jul 07 '20 at 02:45
1

Collapsing using "<br> " seems to do the trick (note the extra space is necessary):

a1 <- c(1, 2, 3)
data <- c(100, 155, -4)
a2 <- c(0, paste(data, collapse = "<br> "), 1000000) 
b <- data.frame(cbind(a1, a2))
width <- 10

formattable(b)

enter image description here

Count Orlok
  • 997
  • 4
  • 13
  • Thanks! I saw
    as html code when looking for a solution, but didn't bother to try it since I didn't think it would work. Lesson learned, I should try everything anyways haha.
    – AnthonyH Jul 07 '20 at 02:49