# [R] Selecting and multiplying

mdvaan mathijsdevaan at gmail.com
Fri Sep 2 00:20:43 CEST 2011

```Hi,

I have created two objects: object c contains yearly "distances" between
cases and object g contains yearly interactions between cases. For each case
and every year I would like to calculate the following value:

Vit = sum(Dabt * Iait * Ibit)

Where Vit is the value of case i in year t, Dabt is the distance between all
cases a and b that have interacted more than 0 times with i, Iait is the
number of times i has interacted with a and Ibit is the number of times i
has interacted with b. So for 8027 in 1999 Vit becomes:

(0.27547644 * 1 * 2) + (0.31481129 * 1 * 1) + (0.09896982 * 2 * 1) =
1.06370381

How do I create a dataframe that accomodates the values for each case in

Example:

library(zoo)
DF1 = data.frame(read.table(textConnection("    B  C  D  E  F  G
8025  1995  0  4  1  2
8025  1997  1  1  3  4
8026  1995  0  7  0  0
8026  1996  1  2  3  0
8026  1997  1  2  3  1
8026  1998  6  0  0  4
8026  1999  3  7  0  3
8027  1997  1  2  3  9
8027  1998  1  2  3  1
8027  1999  6  0  0  2
8028  1999  3  7  0  0
8029  1995  0  2  3  3
8029  1998  1  2  3  2
8029  1999  6  0  0  1"),head=TRUE,stringsAsFactors=FALSE))

a <- read.zoo(DF1, split = 1, index = 2, FUN = identity)
sum.na <- function(x) if (any(!is.na(x))) sum(x, na.rm = TRUE) else NA
b <- rollapply(a, 3,  sum.na, align = "right", partial = TRUE)
newDF <- lapply(1:nrow(b), function(i)
prop.table(na.omit(matrix(b[i,], nc = 4, byrow = TRUE,
dimnames = list(unique(DF1\$B), names(DF1)[-1:-2]))), 1))
names(newDF) <- time(a)
c<-lapply(newDF, function(mat) 1-tcrossprod(mat / sqrt(rowSums(mat^2))))
c<-lapply(c, function (x) ifelse(x<0.000000111, 0, x))

DF2 = data.frame(read.table(textConnection("  A  B  C
80  8025  1995
80  8026  1995
80  8029  1995
81  8026  1996
82  8025  1997
82  8026  1997
83  8025  1997
83  8027  1997
90  8026  1998
90  8027  1998
90  8029  1998
84  8026  1999
84  8027  1999
85  8028  1999

e <- function(y) crossprod(table(DF2[DF2\$C %in% y, 1:2]))
years <- sort(unique(DF2\$C))
f <- as.data.frame(embed(years, 3))
g<-lapply(split(f, f[, 1]), e)

--
View this message in context: http://r.789695.n4.nabble.com/Selecting-and-multiplying-tp3784901p3784901.html
Sent from the R help mailing list archive at Nabble.com.

```