Question

I have the following data:

A    B
1    101
1    102
3    104
4    104

And would like to transform it into this:

     101   102   104
1      1     1     0
3      0     0     1
4      0     0     1

What is this transformation called and what kind of package should I be looking for?

Was it helpful?

Solution

You can use xtabs from base R to do this:

df <-  read.table(text="A    B
+ 1    101
+ 1    102
+ 3    104
+ 4    104", header=T)

xtabs(~ A + B, df)

#   B
#A   101 102 104
#  1   1   1   0
#  3   0   0   1
#  4   0   0   1

Another way of doing it would be to use table:

table(df)

#   B
#A   101 102 104
#  1   1   1   0
#  3   0   0   1
#  4   0   0   1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top