Greetings R folks,
I am stuck on a problem that I suspect can be solved somewhat easily.
I have social network data stored in dyads as below, where the numbers
representing ego and alter are identifiers, so that number 1 as an ego is the
same person as number 1 as an alter etc.
ego alter
1 1 2
2 1 3
3 2 1
4 2 4
5 3 1
6 3 2
7 3 4
8 3 6
9 4 1
10 5 3
11 5 6
12 6 4
What I would like to do is to create new dyads which match up the ego with the
alter's alters as below (preferably removing dyads in which ego and alter2
are the same):
ego alter2
1 1 4
2 1 2
3 1 4
4 1 6
5 2 3
6 2 1
7 3 2
8 3 1
9 3 4
10 3 1
11 3 4
12 4 2
13 4 3
14 5 1
15 5 2
16 5 4
17 5 6
18 5 4
19 6 1
Any suggestions as to how to do this would be greatly appreciated.
Holly
William Dunlap
2012-Mar-21 04:50 UTC
[R] help matching observations for social network data
Your data.frame is
d <- data.frame(
ego = c(1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5, 6),
alter = c(2, 3, 1, 4, 1, 2, 4, 6, 1, 3, 6, 4))
and you want to get
e <- data.frame(
ego = c(1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 6),
alter2 = c(4, 2, 4, 6, 3, 1, 2, 1, 4, 1, 4, 2, 3, 1, 2, 4, 6, 4, 1))
Try using merge() and removing the entries where
ego and alter of alter are the same:
f <- function(d) {
tmp <- merge(d, d, by.x = "alter", by.y="ego") #
note this gives 'tmp' illegal duplicate column names
tmp2 <- tmp[ tmp[,2] != tmp[,3], c(2,3)]
colnames(tmp2)[2] <- "alter2"
tmp2
}
I think that f(d) and e contain the same set of rows, although
they are ordered differently.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at
r-project.org] On Behalf
> Of Holly Shakya
> Sent: Tuesday, March 20, 2012 9:15 PM
> To: r-help at r-project.org
> Subject: [R] help matching observations for social network data
>
> Greetings R folks,
>
> I am stuck on a problem that I suspect can be solved somewhat easily.
>
> I have social network data stored in dyads as below, where the numbers
representing
> ego and alter are identifiers, so that number 1 as an ego is the same
person as number 1
> as an alter etc.
>
>
> ego alter
> 1 1 2
> 2 1 3
> 3 2 1
> 4 2 4
> 5 3 1
> 6 3 2
> 7 3 4
> 8 3 6
> 9 4 1
> 10 5 3
> 11 5 6
> 12 6 4
>
> What I would like to do is to create new dyads which match up the ego with
the alter's
> alters as below (preferably removing dyads in which ego and alter2 are the
same):
>
> ego alter2
> 1 1 4
> 2 1 2
> 3 1 4
> 4 1 6
> 5 2 3
> 6 2 1
> 7 3 2
> 8 3 1
> 9 3 4
> 10 3 1
> 11 3 4
> 12 4 2
> 13 4 3
> 14 5 1
> 15 5 2
> 16 5 4
> 17 5 6
> 18 5 4
> 19 6 1
>
>
> Any suggestions as to how to do this would be greatly appreciated.
>
> Holly
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.