In R
the function ftable()
creates by default a table with a so called ragged appearance:
data(UCBAdmissions)
ftable(UCBAdmissions)
...
Dept A B C D E F
Admit Gender
Admitted Male 512 353 120 138 53 22
Female 89 17 202 131 94 24
Rejected Male 313 207 205 279 138 351
Female 19 8 391 244 299 317
Rows and columns are “ragged” in the sense that labels are only displayed when they change, with the obvious convention that rows are read from top to bottom and columns are read from left to right. (https://cran.r-project.org/doc/manuals/r-devel/R-data.html#Flat-contingency-tables)
Question:
How can I get same "ragged" appearance for a normal data.frame
object?
Reproducible example:
before= data.frame(C1= c(rep("A", 5), rep("L", 2)),
C2= c("B", rep("E", 3), rep("K", 2), "L"),
C3= c("C", "F", rep("H", 5)),
C4= c("D", "G", "I", rep("J", 4)),
stringsAsFactors = FALSE)
before
...
C1 C2 C3 C4
1 A B C D
2 A E F G
3 A E H I
4 A E H J
5 A K H J
6 L K H J
7 L L H J
How does a function look like which converts the object before
to a new object after
of class data.frame
, which is printed to console with print(after)
as follows...
C1 C2 C3 C4
1 A B C D
2 E F G
3 H I
4 J
5 K H J
6 L K H J
7 L H J
If necessary, it is acceptable that the left out data are lost for this presentation format.
Maybe not the most elegant solution (a. lots of
for
loops, b. coercing any type of column to character, c. no input assertions, d. slow, etc.), but following functionrag_blank
seems to basically work as requested on the example:...
In some cases applying blanks is not appropriate, then this may be helpful:
...
More busy example:
...
In case there are more elegant solutions, appreciate your feedback.