Calculate conditional correlation of row sums in loop

Viewed 140

I have: data (questionnaire) of five variables (V1 through V5), each answered on a scale from 1 to 6.

I'd like to calculate the following correlations: Take V1 as condition, and for each possible V1 value calculate the correlation of (V2 + V3) with (V4 plus V5). In effect: look only at cases where V1 = 1 and calculate cor of V2+V3 with V4+V5; then for V1 = 2 and so on.

I'd like to write it in a loop, but can't get it to work. I think it would be possible to manually add columns containing the sums and then sort the data with dplyr package, but that seems very clumsy.

**Example Data**    

 ID     V1    V2     V3     V4     V5
61617   3     4      2      2      3
61618   3     3      3      5      5
61620   4     5      4      2      3
61621   2     5      2      4      1
61622   2     3      4      4      3
61623   3     5      2      2      3
61624   1     2      2      1      1

Even to start with, I've manually tried the unconditional correlation of sums cor(sum(V$V2,V$V3),sum(V$V4,V$V5),use="pairwise.complete"), which yielded NA, too.

I've tried ifelse and rowSums statements, but to no avail. How can I approach this as a non-programmer?

2 Answers

It can be achieved easily by the dplyr pacakge.

library(dplyr)

df %>%
  group_by(V1) %>%
  summarise(cor = cor(V2 + V3, V4 + V5))

# # A tibble: 6 x 2
#      V1     cor
#   <int>   <dbl>
# 1     1  0.111 
# 2     2  0.0434
# 3     3  0.140 
# 4     4  0.0791
# 5     5 -0.0298
# 6     6  0.103

Data

set.seed(123)
df <- as.data.frame(matrix(sample(1:6, 500, T), 100))

#   V1 V2 V3 V4 V5
# 1  3  2  5  3  5
# 2  6  4  6  1  3
# 3  3  2  5  5  4
# 4  2  2  3  6  2
# 5  2  6  3  6  5
# … with 95 more rows

One option:

sapply(
  split(V, V$V1),
  function(X) {
    with(X, cor(V2 + V3, V4 + V5, use="pairwise.complete"))
  }
)
#         2          3 
# 0.9176629 -0.4714045 

Reproducble data (modified to have fewer groups):

V <- data.frame(
  ID = c(61617L, 61618L, 61620L, 61621L, 61622L, 61623L, 61624L), 
  V1 = c(3L, 3L, 3L, 2L, 2L, 3L, 2L), 
  V2 = c(4L, 3L, 5L, 5L, 3L, 5L, 2L), 
  V3 = c(2L, 3L, 4L, 2L, 4L, 2L, 2L), 
  V4 = c(2L, 5L, 2L, 4L, 4L, 2L, 1L), 
  V5 = c(3L, 5L, 3L, 1L, 3L, 3L, 1L)
)
Related