Home > front end >  correlation of a vector across all column in R (dplyr)
correlation of a vector across all column in R (dplyr)

Time:02-27

I have a data frame in R (taken from the dplyr's site here):

library(dplyr)
gdf <-
  tibble(g = c(1, 1, 2, 3), v1 = 10:13, v2 = 20:23) %>%
  group_by(g)
gdf

Resulting to:

# A tibble: 4 × 3
# Groups:   g [3]
      g    v1    v2
  <dbl> <int> <int>
1     1    10    20
2     1    11    21
3     2    12    22
4     3    13    23

Now I have a vector :

y <- rnorm(4);y

I want to measure the correlation of y with v1 and the correlation of y with v2 simultaneously.

The across() function might do the job

gdf %>% mutate(across(v1:v2, ~ cor(.x,y)))

but R reports me an error :

Error: Problem with `mutate()` input `..1`.
ℹ `..1 = across(v1:v2, ~cor(.x, y))`.
x incompatible dimensions
ℹ The error occurred in group 1: g = 1.
Run `rlang::last_error()` to see where the error occurred.

CodePudding user response:

Since cor() requires same dimension for both x and y, you cannot group rows together, otherwise, they will not have 4 elements to match with 4 values in y.

Prepare data and library

library(dplyr)

gdf <-
  tibble(g = c(1, 1, 2, 3), v1 = 10:13, v2 = 20:23)

y <- rnorm(4)
[1] 0.59390132 0.91897737 0.78213630 0.07456498

mutate()

If you want to keep v1 and v2 in the output, use the .names argument to indicate the names of the new columns. {.col} refers to the column name that across is acting on.

gdf %>% mutate(across(v1:v2, ~ cor(.x,y), .names = "{.col}_cor"))

# A tibble: 4 x 5
      g    v1    v2 v1_cor v2_cor
  <dbl> <int> <int>  <dbl>  <dbl>
1     1    10    20 -0.591 -0.591
2     1    11    21 -0.591 -0.591
3     2    12    22 -0.591 -0.591
4     3    13    23 -0.591 -0.591

summarise()

If you only want the cor() output in the results, you can use summarise

gdf %>% summarize(across(v1:v2, ~ cor(.x,y)))

# A tibble: 1 x 2
      v1     v2
   <dbl>  <dbl>
1 -0.591 -0.591

CodePudding user response:

Using base R:

cor(gdf[,-1], y)

#>         [,1]
#> v1 0.5080586
#> v2 0.5080586

Another possible solution, based on purrr::map_dfc:

library(tidyverse)

gdf <-
  tibble(g = c(1, 1, 2, 3), v1 = 10:13, v2 = 20:23)

set.seed(123)
y <- rnorm(4)

map_dfc(gdf[,-1], ~ cor(.x, y))

#> # A tibble: 1 × 2
#>      v1    v2
#>   <dbl> <dbl>
#> 1 0.508 0.508
  • Related