I'm trying to reshape my data using dcast. I'm working with samples where each sample has 10-30 sample units. I can't have my data aggregate.
My data is in this format:
ID total
sample_1 1
sample_1 0
sample_1 2
sample_1 1
sample_1 0
sample_1 0
sample_1 2
sample_1 1
sample_1 0
sample_1 2
sample_1 1
sample_1 4
sample_2 2
sample_2 1
sample_2 2
sample_2 0
sample_2 0
sample_2 0
sample_2 1
sample_2 2
sample_2 1
sample_2 4
sample_2 5
sample_2 2
sample_2 1
sample_3 0
sample_3 0
sample_3 1
sample_3 2
sample_3 1
sample_3 0
sample_3 2
sample_3 1
sample_3 4
sample_3 5
sample_3 1
sample_3 1
sample_3 0
sample_3 0
sample_3 1
And I want it to looks like it:
sample_1 sample_2 sample_3
1 2 0
0 1 0
2 2 1
1 0 2
0 0 1
0 0 0
2 1 2
1 2 1
0 1 4
2 4 5
1 5 1
4 2 1
1 0
0
1
Where my sample ID's turn into different columns.
I tried in several ways but R keep aggregating it.
You can do this with
dcast()
but you have to add row numbers for eachID
.The
data.table
package is another package besidesreshape2
which implementsdcast()
.data.table
has a handyrowid()
function to generate unique row ids within each group. WIth that, we get:However, I recommend to continue any data processing in long format and use grouping. That's much easier than to work on individual columns. For instance,
Data