0

I have this data:

structure(list(id = 1:6, arthritis = c(1L, 0L, 0L, 0L, 0L, 1L
), asthma = c(0L, 0L, 0L, 0L, 0L, 0L), cancer = c(0L, 0L, 0L, 
0L, 0L, 0L), cerebvascdz = c(0L, 0L, 0L, 0L, 0L, 0L), chf = c(0L, 
0L, 0L, 0L, 0L, 0L), crf = c(0L, 0L, 0L, 0L, 0L, 0L), copd = c(0L, 
0L, 0L, 0L, 0L, 0L), depression = c(0L, 0L, 0L, 1L, 1L, 1L), 
    diabetes = c(0L, 0L, 0L, 0L, 0L, 0L), hyperlipid = c(1L, 
    0L, 1L, 0L, 1L, 0L), htn = c(1L, 0L, 1L, 1L, 0L, 1L), ihd = c(1L, 
    0L, 0L, 0L, 0L, 0L), obesity = c(0L, 0L, 0L, 0L, 0L, 0L), 
    osteoporosis = c(0L, 0L, 0L, 0L, 0L, 1L)), row.names = c(NA, 
6L), class = "data.frame")

which contains an id for a patient. all the rest of the columns are comorbidities that the patient might have, designated as a boolean. I'm trying to use the gather method to flip the table around, as shown like this. Every comorbidity that the patient has is supposed to be populated on the right with the patient id on the left.

I'm pretty sure I'm supposed to be using the gather function, but I can't seem to get this working. Does anyone have any insight into what I should be doing to have the frame switch to the required format?

Phil Robinson
  • 427
  • 1
  • 4
  • 12
  • 1
    (1) Please do not post an image of code/data/errors: it cannot be copied or searched (SEO), it breaks screen-readers, and it may not fit well on some mobile devices. Ref: https://meta.stackoverflow.com/a/285557/3358272. I suggest you provide sample data by editing your question with the output from `dput(head(x))` (ref: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info). (2) You said you thought of the `gather` function, what you have tried? It helps to start with code you're using. – r2evans Feb 15 '19 at 18:42

1 Answers1

1

Here is the proper code

pmh %>% 
  gather(diagnosis,num, arthritis:osteoporosis) %>% 
  arrange(id) %>% 
  filter(num == 1)

I'm new to R and I think I had misunderstood the first argument that gather takes.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Phil Robinson
  • 427
  • 1
  • 4
  • 12