0

I am trying to convert a list of observation for censored data to a proper format for survival analysis in R. To give an exemple, the code should transform like this.

 event.6mo event.12mo event.24mo
1         0          0          0
2         0          1         NA
3         0          0          1

where each line describes a patient, 0= no event at that time point, 1=event and columns refer to 6, 12, 24 months observations.

and transform to:

  event censored
1    24    0
2    12    1
3    24    1

Thanks in advance!

Sotos
  • 51,121
  • 6
  • 32
  • 66
  • What is your question? This reads like a code request for free. Please post your earnest attempt at a solution so we can help with specific issues. – Parfait Feb 12 '20 at 14:50

2 Answers2

1

You can try colSums with stack, i.e.

stack(colSums(d3, na.rm = TRUE))
#  values        ind
#1      0  event.6mo
#2      1 event.12mo
#3      1 event.24mo

DATA

dput(d3)
structure(list(vent.6mo = c(0L, 0L, 0L), event.12mo = c(0L, 1L, 
0L), event.24mo = c(0L, NA, 1L)), class = "data.frame", row.names = c("1", 
"2", "3"))
Sotos
  • 51,121
  • 6
  • 32
  • 66
0

An option with tidyverse, where we pivot to 'long' format, then grouped by the 'name' get the sum of 'value' column

library(dplyr)
library(tidyr)
pivot_longer(d3, everything()) %>%
   group_by(name) %>% 
   summarise(value = sum(value, na.rm = TRUE))
# A tibble: 3 x 2
#  name       value
#  <chr>      <int>
#1 event.12mo     1
#2 event.24mo     1
#3 vent.6mo       0

Or it can be also done by first getting the sum of all columns with summarise_all and then reshape to 'long' format

d3 %>%
   summarise_all(sum, na.rm = TRUE) %>% 
   pivot_longer(everything())

data

d3 <- structure(list(vent.6mo = c(0L, 0L, 0L), event.12mo = c(0L, 1L, 
0L), event.24mo = c(0L, NA, 1L)), class = "data.frame", row.names = c("1", 
"2", "3"))
akrun
  • 874,273
  • 37
  • 540
  • 662