I have a data set in R as follows
ID Variable1 Variable2 Choice
1 1 2 1
1 2 1 0
2 2 1 1
2 2 1 1
I need to get the output table for it as under
Id Variable1-1 Variable1-2 Variable2-1 Variable2-2
1 1 0 0 1
2 0 2 2 0
Note that only those rows are counted where the choice is 1 (choice is a binary variable, however other variables have any integer values). The aim is to have as many columns for a variable as its levels.
Is there a way I can do this in R?
You could use
meltanddcastfrom thereshape2package:First melt the data.frame, selecting only those rows where
Choice == 1and removing theChoicecolumnThen cast the melted data.frame, using
lengthas the aggregation function