I have a huge data in R
that I am trying to reshape it in an efficient way. As you see, the changes happen in column Med
and Num
. BTW, I have already tried to find a rigid answer but I was not successful.
Any idea would be great!
Thanks.
Original shape:
User Date Sex Age Ethic Med Num Diag Dis Doc Month
27168 1/1/2002 1 49 NULL 42506 1 2000 0 13545 1
27168 1/1/2002 1 49 NULL 32603 9 2000 0 13545 1
27168 1/1/2002 1 49 NULL 32602 5 2000 0 13545 1
27168 1/1/2002 1 49 NULL 34533 1 2000 0 13545 1
12335 2/1/2002 0 87 2 42506 2 8654 2 34568 1
12335 2/1/2002 0 87 2 65873 4 8654 2 34568 1
Desired Shape:
User Date Sex Age Ethic 42506 32603 32602 34533 65873 Diag Dis Doc Month
27168 1/1/2002 1 49 NULL 1 9 5 1 0 2000 0 13545 1
12335 2/1/2002 0 87 2 2 0 0 0 4 8654 2 34568 1
df %>%
pivot_wider(names_from = Med, values_from = Num, values_fill = 0)
# A tibble: 2 x 14
User Date Sex Age Ethic Diag Dis Doc Month `42506` `32603` `32602` `34533` `65873`
<int> <chr> <int> <int> <chr> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 27168 1/1/2002 1 49 NULL 2000 0 13545 1 1 9 5 1 0
2 12335 2/1/2002 0 87 2 8654 2 34568 1 2 0 0 0 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.