Search code examples
rlistformattingsubset

How to remove an element from a list in R while maintaining the original list print formatting?


I've searched far and wide on Stack Overflow and online generally on how to remove specific elements from a list and I've partly figured out how to do this. However, when I remove an element from this example list, I lose the original nice formatting of the list. Let me explain in the image that follows. How do I remove the "Call" element and the text that follows it ("survdiff(formula = Surv(time, status) ~ sex, data = lung)"), while retaining the original formatting?

Example code is posted at the bottom.

enter image description here

Example code:

library(survival)
library(survmine)

fit <- survfit(Surv(time, status) ~ sex, data = lung)
surv_diff <- survdiff(Surv(time, status) ~ sex, data = lung)
surv_diff

str(surv_diff)

test <- surv_diff[-7] # trying to remove the "Call" element and all its text

Solution

  • When you remove that element, you remove the class attribute. You can place it back like this:

    class(test) <- "survdiff"