How to restructure this data ?

Hi,
I have this data:

data1 <- tibble::tribble(
 ~Patient, ~Drug,
 "JohnX", "Alpha",
 "JohnX", "Gama",
 "JohnX", "Pana",
 "JohnX", "Sega",
 "MikeX", "Sega",
 "MikeX", "Zole",
 "MikeX", "Dol")

I want to restructure this data so it would look like this:


Thank you for your help.

data1 <- tibble::tribble(
  ~Patient, ~Drug,
  "JohnX", "Alpha",
  "JohnX", "Gama",
  "JohnX", "Pana",
  "JohnX", "Sega",
  "MikeX", "Sega",
  "MikeX", "Zole",
  "MikeX", "Dol") %>%
  # add 1 to all the data points
  mutate(Value = 1)

# convert to "wide" format, with Drugs as column names
data2 = pivot_wider(data1,
                    names_from = Drug, 
                    values_from = Value,
                    values_fill = 0)
data2

# A tibble: 2 x 7
  Patient Alpha  Gama  Pana  Sega  Zole   Dol
  <chr>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 JohnX       1     1     1     1     0     0
2 MikeX       0     0     0     1     1     1

How about this?

data1 <- tibble::tribble(
  ~Patient, ~Drug,
  "JohnX", "Alpha",
  "JohnX", "Gama",
  "JohnX", "Pana",
  "JohnX", "Sega",
  "MikeX", "Sega",
  "MikeX", "Zole",
  "MikeX", "Dol")

table(data1)
#>        Drug
#> Patient Alpha Dol Gama Pana Sega Zole
#>   JohnX     1   0    1    1    1    0
#>   MikeX     0   1    0    0    1    1

Thank you very much to both of you, how can I assign solution to both of you ?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.