0

I have the following dataset:

ID Age
1 19
1 22
2 20
2 21

And I would like to turn it into this:

Age ID=1 ID=2
19 1 na
20 na 1
21 na 1
22 1 na

How can I do that?

I have tried both with t() function and spread() but I was not able to arrive to a decent result

  • 1
    `mutate(quux, value = 1) %>% pivot_wider(Age, names_from = "ID")` (or using `reshape2`, with `transform(quux, value = 1) |> reshape2::dcast(Age ~ ID, value.var = "value")`). (The `quux` is the data.frame object.) – r2evans Apr 06 '23 at 20:18
  • using the dplyr code I get the following error: Values from `value` are not uniquely identified; output will contain list-cols. * Use `values_fn = list` to suppress this warning. * Use `values_fn = {summary_fun}` to summarise duplicates. * Use the following dplyr code to identify duplicates. {data} %>% dplyr::group_by(age, ID) %>% dplyr::summarise(n = dplyr::n(), .groups = "drop") %>% dplyr::filter(n > 1L) – user13195765 Apr 06 '23 at 20:26
  • 1
    consider `xtabs(~Age+ID, df)` – Onyambu Apr 06 '23 at 20:32
  • 1
    @user13195765, it works with the data as you provided it, so I don't konw what's different about your data. My guess is that you don't have the uniquness you expect in your data. Does `count(quux, ID, Age) %>% filter(n > 1)` return any rows? – r2evans Apr 06 '23 at 20:47

0 Answers0