r - How to pairwise compare values referring to distinct elements in two matrices of different formats? -


i've got set of objects, let's ids 'a' 'j'. , i've got 2 data frames following way (as can see, second data frame symmetric):

df1 <- data.frame(id = letters[1:5], var = c(9,13,15,11,28)) df2 <- as.data.frame(matrix(data = c(na,42,83,74,84,42,na,26,69,9,83,26,na,67,95,74,69,67,na,6,84,9,95,6,na), ncol = 5, nrow = 5, dimnames = list(df1$id, df1$id))) 

for example, take objects 'b' , 'e'. want know: 13+28 (from df1) less 9 (from df2)? i'd know pairs of objects. output should be

(a) logical data frame structured df2 and

(b) number of "true" values.

most of time need result (b), need (a). if (b) can calculated without (a) , if faster, i'd have both algorithms in order select suitable 1 dependent on output need answer particular question.

i'm comparing around 2000 objects, algorithm should reasonably fast. far i've been able implement 2 nested for-loops awfully slow. bet there nicer way this, maybe exploiting vectorisation.

this looks like:

df3 <- as.data.frame(matrix(data = na, ncol = nrow(df1), nrow = nrow(df1),                             dimnames = list(df1$id, df1$id)))  (i in 2:nrow(df3)){   (j in 1:(i-1)){     sum.val <- df1[df1$id == rownames(df3)[i], "var"] + df1[df1$id == names(df3)[j], "var"]     df3[i,j] <- sum.val <= df2[i,j]   } } 

#

is want?

df3 <- outer(df1$var, df1$var, "+") df3  df4 <- df3 < df2 df4  sum(df4, na.rm = true) 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -