【问题标题】:Loop for doing multiple correlations on dataset in R在 R 中对数据集进行多重相关的循环
【发布时间】:2021-04-28 18:39:20
【问题描述】:
我有一个包含 x 列的数据集,由测试结果组组成,例如 test1_1、test1_2 等。每组测试都有不同数量的测试结果与之关联,因此实际数字不一样在每个测试中。最后一列是我的目标变量。我正在寻找确定哪些测试与目标变量相关,但我也想为每组测试创建数据集。我还将针对目标变量绘制每个测试的相关图。我怀疑我可以在 for/while 循环中用几行代码实现所有这些,但是,我不确定从哪里开始。
【问题讨论】:
标签:
r
for-loop
dplyr
while-loop
correlation
【解决方案1】:
使用lapply 可以这样实现:
library(dplyr)
library(corrplot)
set.seed(42)
dataset <- data.frame(
test1_1 = runif(20),
test1_2 = runif(20),
test2_1 = runif(20),
test2_2 = runif(20),
Target = runif(20)
)
test_cols <- gsub("_\\d+$", "", names(dataset))
test_cols <- test_cols[grepl("^test", test_cols)]
test_cols <- unique(test_cols)
test_cols <- setNames(test_cols, test_cols)
test_fun <- function(x, test) {
x <- x %>%
select((starts_with(test)) | matches("Target"))
cor(x)
}
cor_test <- lapply(test_cols, test_fun, x = dataset)
cplot <- lapply(cor_test, corrplot)
【解决方案2】:
这类似于@stefan 的回答,使用split.default 按列名中的模式拆分列。
tmp <- dplyr::select(dataset, -Target)
list_plot <- lapply(split.default(tmp, sub('_.*', '', names(tmp))), function(x) {
corrplot::corrplot(cor(cbind(x, Target = dataset$Target)))
})