# Merge one subject observations to all others

1101 views
3

I'm attempting to remove a subject from the data set and then subsequently merge them in with the others so that their values at each time point can be compared to everyone else.

This is what the data looks like:

``````subject <- rep(1:5, each = 20)
seconds <- rep(1:20, each = 20)
variable <- rnorm(n = subject, mean = 20, sd = 10)
d <- data.frame(subject, seconds, variable)
``````

Then, I am removing subject four from the data and trying to merge them back to compare them to each of the other subjects:

``````four <- subset(d, subject == 4)
d2 <- subset(d, subject != 4)
``````

I've tried these two bits of code but haven't gotten either of them to work:

``````merge(d2, four, by = "seconds")
merge(d2, four, by = "seconds", all.x = T)
``````

This example is a small data set so I could do it by hand but the real data is very large, over several years, so I need to be able to code it out in `dply` (most likely) so that I can make it work over different conditions. But, I figured I'd start with something simple and go from there.

Can you add a quite outline of what your expected outcome looks like? Are you aware of the output of `table(d\$subject, d\$seconds)`, i.e. that only subject 4 has entries "seconds == 4"?

13

The problem in your code comes from the fact that only subjects `4` have values that satisfy `seconds == 4`. See:

``````subject <- rep(1:5, each = 20)
seconds <- rep(1:20, each = 20)
d <- data.frame(subject, seconds)
with(d, table(subject, seconds))
seconds
subject  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
1 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0
2  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0
3  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0
4  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0
5  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20
``````

posted this