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
  • 365
  • 1
  • 2
  • 11
  • 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
    Additionally, though you are within your rights to not do so, please consider going back and [accepting](https://stackoverflow.com/help/someone-answers) answers to your previous questions; doing so not only provides a little perk to the answerer with some points, but also provides some closure for readers with similar questions. Though you can only accept one answer, you have the option to up-vote as many as you think are helpful. – r2evans Feb 15 '19 at 18:44

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
  • 21,987
  • 13
  • 41
  • 69
Phil Robinson
  • 365
  • 1
  • 2
  • 11