簡體   English   中英

如何計算 R 中多列中每個標記單元格的相關性和散點圖

[英]How to calculate correlations and scatterplots for each marked cell in multiple columns in R

我有一個看起來像這樣的日期框架:

ID 第 1 列 第 2 欄 第 3 欄 第 n 列 主變量 1 主變量 2
1個 0 1個 0 ... -0.5 8個
2個 1個 0 0 ... 2.5 14
3個 0 1個 0 ... 4個 6個
... ... ... ... ... ... ...

我想關聯兩個主要變量,並為列中每個標記的單元格 (= 1) 制作散點圖。 例如,在第 2 列中,第一行和第三行標記為 1。因此只有主變量的第一個和第三個值應該 go 進入相關計算。 我的想法是使用列名創建 e 向量並將其放入相關性 function 但結果我只能從第一列的標記單元格中獲取相關值。

Cor(
     Data_frame[which(Data_frame[,column]==1),"main_variable_1"],
     Data_frame[which(Data_frame[,column]==1),"main_variable_2"],
     use = "pairwise.complete.obs"
   )

有人知道如何解決這個問題嗎?

library(tidyverse)
library(broom)

data <- tribble(
  ~ID, ~Column.1, ~Column.2, ~Column.3, ~Column.n, ~Main.variable.1, ~Main.variable.2,
  1L, 0L, 1L, 0L, "...", -0.5, 8L,
  2L, 1L, 0L, 0L, "...", 2.5, 14L,
  3L, 0L, 1L, 0L, "...", 4, 6L,
  3L, 0L, 1L, 0L, "...", 4, 6L,
  3L, 0L, 1L, 0L, "...", 4, 6L,
  3L, 0L, 1L, 0L, "...", 4, 6L,
)

data %>%
  colnames() %>%
  keep(~ .x %>% str_detect("^Column\\.[0-9]+$")) %>%
  enframe() %>%
  mutate(
    cor_test = value %>% map(possibly(~ {
      data %>%
        filter(across(matches(.x), ~ .x == 1)) %>%
        cor.test(~ Main.variable.1 + Main.variable.2, data = .) %>%
        tidy()
    }, NA))
  ) %>%
  unnest(cor_test)
#> Warning: Using `across()` in `filter()` is deprecated, use `if_any()` or
#> `if_all()`.

#> Warning: Using `across()` in `filter()` is deprecated, use `if_any()` or
#> `if_all()`.

#> Warning: Using `across()` in `filter()` is deprecated, use `if_any()` or
#> `if_all()`.
#> # A tibble: 3 × 10
#>    name value    estimate statistic p.value parameter conf.low conf.high method 
#>   <int> <chr>       <dbl>     <dbl>   <dbl>     <int>    <dbl>     <dbl> <chr>  
#> 1     1 Column.1       NA        NA      NA        NA       NA        NA <NA>   
#> 2     2 Column.2       -1      -Inf       0         3       -1        -1 Pearso…
#> 3     3 Column.3       NA        NA      NA        NA       NA        NA <NA>   
#> # … with 1 more variable: alternative <chr>

reprex package (v2.0.0) 創建於 2022-04-14

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM