0

I have a data in R. I want to calculate correlation each value in column "NAME" and each value with INC:

DATA enter image description here

RESULTS I NEED enter image description here

I use this code cor() but the results don't like I think

round(cor(DATA_QD[-c(1,19)] ),
      digits = 2 # rounded to 2 decimals) 

please help me. Thank

harre
  • 7,081
  • 2
  • 16
  • 28
  • 3
    Please add data directly instead of pictures. See: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – harre Jul 22 '22 at 15:08
  • 3
    Welcome to SO. Please don't upload code, error messages, results or data as images for [these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557) - and [these](https://xkcd.com/2116/). Also, note that the correlation between two *values* (ie scalars, for example `cor(0.1, 0.3)`) is undefined. You can only calculate a correlation between two *vectors*. Please clarify what your expected output actually is. – Limey Jul 22 '22 at 15:10
  • Does this answer your question? [Calculate correlations between data.frame columns and assign output to list](https://stackoverflow.com/questions/70597946/calculate-correlations-between-data-frame-columns-and-assign-output-to-list) – user438383 Jul 22 '22 at 15:15

1 Answers1

0

With real numbers the output should make sense.

library(tidyverse)

df <- tibble(
  name = c("CVC","CVC", 
           "CVCC", "CVCC", 
           "TN", "TN"), 
  Value1 = c(1,2,3,4,5,8),
  Value2 = c(6,7,8,9,10,10), 
  Value3 = c(8,9,10,11,12,12),
  INC = c(2,6,9,10,11,15)
)

df %>% 
  group_by(name) %>%
  summarise(across(Value1:Value3, ~ cor(.x, INC)))

# A tibble: 3 x 4
  name  Value1 Value2 Value3
  <chr>  <dbl>  <dbl>  <dbl>
1 CVC        1      1      1
2 CVCC       1      1      1
3 TN         1     NA     NA
Warning messages:
1: In cor(Value2, INC) : the standard deviation is zero
2: In cor(Value3, INC) : the standard deviation is zero

For CVC the correlation is cor(c(1, 2), c(2, 6)) = 1

Chamkrai
  • 5,912
  • 1
  • 4
  • 14