我试图找到一种方法来在r中进行嵌套的for循环,以获取与此相关的所有可能组合:
cor(y, column1* column2)
,cor(y, column1* column3)
,cor(y, column1* column4)
依此类推
这是我到目前为止尝试过的:
for(i in 1:length(dataframe))
{
for(j in 1:length(dataframe))
{
joint_correlation(i,j)=cor(y ~ dataframe(i) * dataframe(j));
}
}
我的数据框有115列,如一个小示例所示:
FG_pct FGA FT FT_pct FTA GP GS GmSc MP ORB
0.625 8 0 0.00 0 1 0 6.6 28.4 2
0.500 4 0 0.00 1 2 0 2.1 17.5 0
0.000 1 0 0.00 0 3 0 1.2 6.6 1
0.500 6 0 0.00 0 4 0 3.6 13.7 1
0.500 2 0 0.00 0 5 0 0.9 7.4 1
我想为列1和列2切换出的每个可能组合找到cor(MP, column1* column2)
的相关性。这样,我就不必分别做每个。如果可能的话,我想将每个相关组合cor(MP, column1* column2)
,cor(MP, column1* column3)
,cor(MP, column2* column4)
等的输出保存在单独的列中。
这是我想要的示例:cor(MP, FG_pct*FT_pct)
编辑:Jean-Claude Arbaut给出了一个更好的答案,对此答案进行了评论。使用cor(df)。
这是我的拙劣答案:使用库corrgram(主要是可视化工具),我们可以轻松地获取数据集中所有相关性组合。示例:
library(corrgram)
#Example data
df <- data.frame(x = rnorm(50, 5, 5),
y = rnorm(50, 2, 5))
df$z <- df$x / df$y
df$abc <- df$x * df$y * df$z
#panel arguments are necessary if you want to visualize correlations
corr <- corrgram(df,
order = F,
lower.panel = panel.cor,
upper.panel = panel.pts,
text.panel = panel.txt,
diag.panel = panel.minmax,
main = "Correlation")
#call corr gives
corr
x y z abc
x 1.00000000 0.07064179 0.1402051 0.89166002
y 0.07064179 1.00000000 0.2495239 0.08024278
z 0.14020508 0.24952388 1.0000000 0.14649093
abc 0.89166002 0.08024278 0.1464909 1.00000000
绝对有更好的方法来使用函数而没有包,但这是在这里的早期,如果您急于获得结果,这可能会很好。
使用corrgram()函数而不分配它的点可以使您很好地看到相关性。
假设您希望每列的相关性乘以其余两列的组合。
我们可以使用combn(names(dat), 2)
放入lapply
中找到相应组合的名称。
combs <- do.call(cbind.data.frame,
lapply("MP", rbind, combn(names(dat)[names(dat) != "MP"], 2)))
combs
# 1 2 3
# 1 MP MP MP
# 2 FG_pct FG_pct FGA
# 3 FGA FT FT
[在另一个lapply
中,我们对名称组合中的数据进行子集处理,并使用公式cor(x1〜x2 * x3)计算cor
。同时,我们将名称paste
d作为公式存储在attr
ibute中,以便稍后记住我们在每次迭代中计算出的结果。
res.l <- lapply(combs, function(x) {
`attr<-`(cor(dat[,x[1]], dat[,x[2]]*dat[,x[3]]),
"what", {
paste0(x[1], ", ", paste(x[2], "*", x[3]))})
})
最后根据属性,我们选择unlist
和setNames
。>>
结果
# MP, FG_pct * FGA MP, FG_pct * FT MP, FGA * FT # 0.2121374 0.2829003 0.4737892
检查:
((请注意,您可以直接将名称,例如MP,FG_pct * FGA放到cor函数中。)
with(dat, cor(MP, FG_pct * FGA)) # [1] 0.2121374 with(dat, cor(MP, FG_pct * FT)) # [1] 0.2829003 with(dat, cor(MP, FGA * FT)) # [1] 0.4737892
要排序,请使用例如
sort(res)
或rev(sort(res))
。
玩具数据:
set.seed(42)
dat <- as.data.frame(`colnames<-`(MASS::mvrnorm(n=1e4,
mu=c(0.425, 4.2, 0.2, 3),
Sigma=matrix(c(1, .3, .7, 0,
.3, 1, .5, 0,
.7, .5, 1, 0,
0, 0, 0, 1), nrow=4),
empirical=T), c("FG_pct", "MP", "FGA", "FT")))