Since I don't have access to your data, I'll create a synthetic data set.
library(tidyverse)
df <- data_frame(A = 1:12,
B = rev(A),
C = 2 * A,
D = 2 * B,
Y = 1:12)
> df
# A tibble: 12 x 5
A B C D Y
<int> <int> <dbl> <dbl> <int>
1 1 12 2 24 1
2 2 11 4 22 2
3 3 10 6 20 3
4 4 9 8 18 4
5 5 8 10 16 5
6 6 7 12 14 6
7 7 6 14 12 7
8 8 5 16 10 8
9 9 4 18 8 9
10 10 3 20 6 10
11 11 2 22 4 11
12 12 1 24 2 12
cor(A,Y) and cor(C,Y) should be 1. cor(B,Y) and cor(D,Y) should be -1.
I would break the dataframe into two pieces:
- the portion you want to loop over (X)
- and the portion that should stay constant (Y)
X <- select(df, -Y)
Y <- select(df, Y)
Now I can use map_df from the purrr package to feed each column of X to cor while setting the y parameter to Y. The output will be a dataframe.
library(purrr)
result <- map_df(X, cor, y = Y)
> result
# A tibble: 1 x 4
A B C D
<dbl> <dbl> <dbl> <dbl>
1 1 -1 1 -1