I\'m a total beginner in R. I have a series of data relating the surnames of married persons.
Id_mar Wife Husband
1 1 Smith Johnson
2 2 Sm
Based on the expected output, we can use table
(as @David Arenburg mentioned in the comments) on factor
converted 'Wife' and 'Husband' columns, specifying the levels
as the sort
ed unique
elements of both the columns ('Un1')
Un1 <- sort(unique(unlist(df1[-1])))
table(factor(df1$Wife, levels=Un1), factor(df1$Husband, levels=Un1))
# Carter Johnson Smith Wang White
# Carter 0 0 0 0 0
# Johnson 0 0 0 0 0
# Smith 1 1 0 0 0
# Wang 0 0 1 0 0
# White 2 0 0 0 0
Or we can use mtabulate
from qdapTools
.
library(qdapTools)
mtabulate(as.data.frame(t(df1[-1])))