簡體   English   中英

計算 data.frame 列之間的相關性並將 output 分配給列表

[英]Calculate correlations between data.frame columns and assign output to list

給定這個data.frame:

 Age <- c(23, 41, 32, 58, 26)
 e <- c(23, 41, 32, 58, 26)
 Ag <- c(23, 41, 32, 58, 26)
 df <- data.frame(Ag,e, Age)

我想使用 cor 來計算 Ag 與 data.frame 中所有其他列之間的相關性(它們不僅有兩個)。 然后將結果返回到一個列表中,其中列的名稱為

>lst
$e
[1] 1

$Age
[1] 1

使用dplyr

summarise允許我們 select 哪些列應用自定義 function 到 - 在這種情況下,除Ag以外的所有列,自定義 function 執行所選列之間的相關性。

library(dplyr)
df %>% summarise(across(-Ag, function(x) cor(x, Ag))) %>% as.list
$e
[1] 1

$Age
[1] 1

使用base R

as.list(cor(df)[1,-1])

-輸出

$e
[1] 1

$Age
[1] 1

暫無
暫無

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

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