I have a data frame with the following format:
name workplace
a A
b B
c A
d C
e D
....
I would like to convert this data frame into an affiliation network in R with the format
A B C D ...
a 1 0 0 0
b 0 1 0 0
c 1 0 0 0
d 0 0 1 0
e 0 0 0 1
...
and I used the following program:
for (i in 1:nrow(A1)) {
a1[rownames(a1) == A1$name[i],
colnames(a1) == A1$workplace[i]] <- 1
}
where A1 is the data frame, and a1 is the affiliation network. However, since I have a large data frame, the above program runs very slow. Is there an efficient way that avoids looping in data conversion?
Thank you very much!
If your data called df
just do:
as.data.frame.matrix(table(df))
# A B C D
# a 1 0 0 0
# b 0 1 0 0
# c 1 0 0 0
# d 0 0 1 0
# e 0 0 0 1
May be this also helps:
m1 <- model.matrix(~0+workplace, data=dat)
dimnames(m1) <- lapply(dat, unique)
as.data.frame(m1)
# A B C D
#a 1 0 0 0
#b 0 1 0 0
#c 1 0 0 0
#d 0 0 1 0
#e 0 0 0 1
来源:https://stackoverflow.com/questions/25780309/converting-data-frame-into-affiliation-network-in-r