0

I was wondering if there might be a way to create a title above a data.frame such that in the output it kind of looks like list("Violations of Rule #1:" = h) in my R code below?

The title is: "Violations of Rule #1:"

h <- data.frame(1:5, 2:6, rep("YofPub", 5))

dimnames(h) <- list("Violations of Rule #1:" = rownames(h), names(h)) # tried no success!

list("Violations of Rule #1:" = h) # similar to this output but not a list!
rnorouzian
  • 7,397
  • 5
  • 27
  • 72
  • 1
    Not clear about what your expected output would look like. – Ronak Shah Nov 12 '19 at 23:58
  • `h` is already a dataframe so I am not sure what different they need. What is the significance of `"Violations of Rule #1:" ` ? – Ronak Shah Nov 13 '19 at 00:31
  • You could probably define a separate `print` method for a different `class` like 'labelleddf`, and store what would normally be the names of the dimnames in an extra attribute. It's a lot of fussing around, but it would work. – thelatemail Nov 13 '19 at 00:40
  • @rnorouzian - something like this - https://stackoverflow.com/questions/22070777/represent-numeric-value-with-typical-dollar-amount-format/22071182 - you would define a separate `print.labdf` , then set `class(h) <- c("labdf", class(h))` . At the moment there is no way to store dimension names in a standard `data.frame` however for the new print method to pick it up. – thelatemail Nov 13 '19 at 00:51

1 Answers1

1

This is ugly, but you can define your own print method that can give you what you want. More details on how this works here: Is there function overloading in R? here: Represent numeric value with typical dollar amount format

h <- data.frame(1:5, 2:6, 3:7)

attr(h, "rclab") <- c("Row label","Column label")

print.labdf <- function(data) {
  dn <- dimnames(data)
  names(dn) <- attr(data, "rclab")
  data <- as.matrix(data)
  dimnames(data) <- dn
  print(data)
}

class(h) <- c("labdf", class(h))

h

#         Column label
#Row label X1.5 X2.6 X3.7
#        1    1    2    3
#        2    2    3    4
#        3    3    4    5
#        4    4    5    6
#        5    5    6    7
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • Do you mean the `""` quotes? If so, you can change the last line of the `print.labdf` function to `print(data, quote=FALSE)`. This is ultimately just giving OP a starting point - the method can be adjusted to give whatever they want output. – thelatemail Nov 13 '19 at 01:16
  • @rnorouzian - possibly, i'm not really across all the complications of defining print methods. There is a relevant discussion here - https://stackoverflow.com/questions/31856189/how-to-let-print-pass-arguments-to-a-user-defined-print-method-in-r however. – thelatemail Nov 13 '19 at 01:57