首页 > 解决方案 > 按组的相关性

问题描述

已经有一些关于此的其他线程。我想实施以下建议的解决方案。

作为示例数据集:

data(Leinhart, package = "carData")
dat <- tibble::rowid_to_column(Leinhardt, var = "ID")
dat$income <- as.numeric(dat$income)
head(dat)

 ID income infant   region oil
  1   3426   26.7     Asia  no
  2   3350   23.7   Europe  no
  3   3346   17.0   Europe  no
  4   4751   16.8 Americas  no
  5   5029   13.5   Europe  no
  6   3312   10.1   Europe  no

我认为,这是其他帖子和我的错误中建议的解决方案。为什么会这样?

library(tidyverse)
library(broom)

dat  %>% 
  group_by(region) %>%
  summarize(correlation = cor(infant, income, method = "sp"))

Fehler in summarize(., correlation = cor(infant, income, method = "sp")) : 
  Argument "by" fehlt (ohne Standardwert)

R 版本:“R 版本 4.0.4 (2021-02-15)” Dplyr 版本:“1.0.4”。

(我已将其发布在另一个问题中,之前我已将其删除,因为有两个单独的问题引起了混乱。)

谢谢你。

标签: rcorrelation

解决方案


这段代码在我的机器上运行:

library(carData)
df <- Leinhardt


df  %>% 
  group_by(region) %>%
  summarize(correlation = cor(infant, income, method = "sp"))

# output
# A tibble: 4 x 2
  region   correlation
  <fct>          <dbl>
1 Africa        -0.129
2 Americas      NA    
3 Asia          NA    
4 Europe        -0.624

# try this code with your machine:

library(ggcorrplot)
model.matrix(~0+., data=df) %>% 
  cor(use="pairwise.complete.obs") %>% 
  ggcorrplot(show.diag = F, type="lower", lab=TRUE, lab_size=2)

应该导致相关矩阵图,如: 在此处输入图像描述


推荐阅读