r语言 - 如何创建一个循环来合并多个数据集,以评估所有可能的组合(双类、三类、多类)



我正在编写一个代码,该代码根据我正在处理的分类模型中涉及的不同类提供具有不同矩阵的输出。因此,我获得了一堆具有相同列名(即相同类(的数据集(未定义数量(,并由"因子"列中报告的因子标识。我想获得它们的所有多种组合,以便比较多种分类并找出哪个是最好的。这里报告了一个我想要实现的示例(例如,在评估 3 个类时,即 3 个不同的数据集(:

frame_x = data.frame(a=c(12,10,3), b=c(6,4,2), c=c(3,62,3),factor=c("x","x","x"))
frame_y = data.frame(a=c(2,13,34), b=c(22,13,36), c=c(22,13,34),factor=c("y","y","y"))
frame_z = data.frame(a=c(36,28,11), b=c(32,24,16), c=c(33,22,17),factor=c("z","z","z"))
frame_x_new = rbind(frame_x,frame_y,frame_z)
frame_x_new$factor = c("x","x","x","other","other","other","other","other","other")
frame_y_new = rbind(frame_y,frame_x,frame_z)
frame_y_new$factor = c("y","y","y","other","other","other","other","other","other")
frame_z_new = rbind(frame_z,frame_x,frame_y)
frame_z_new$factor = c("z","z","z","other","other","other","other","other","other")
frame_x<-frame_x_new
frame_y<-frame_y_new
frame_z<-frame_z_new

如果我有 3 个数据集,我想获得以下信息,以测试 x 与 y+z、y 与 x+z 和 z 与 x+y 的不同组合。我想使用循环来执行此操作,因为我可能还有更高的(例如 4 个数据集,我希望有 x 与 y+z+w 等(或更低的(例如 2 个数据集,x 对 y(数据帧的数量。此外,所涉及的变量数量可能因评估数据集而异。 谢谢你的帮助。

以下函数执行问题要求的操作。
它需要 2 个参数

  • pattern是数据框名称的正则表达式模式。
  • sep分隔 DF 的名称并定义后缀。

请注意,原始数据集将更改。

fun <- function(pattern, sep = "_"){
frame_list <- ls(pattern = pattern, envir = .GlobalEnv)
suffix <- sapply(strsplit(frame_list, sep), '[[', 2)
df_list <- mget(frame_list, envir = .GlobalEnv)
sa <- seq_along(df_list)
res <- lapply(sa, function(i){
n <- nrow(df_list[[i]])
tmp <- do.call(rbind, df_list[c(i, sa[-i])])
tmp$factor <- c(rep(suffix[i], n),
rep("other", nrow(tmp) - n))
row.names(tmp) <- NULL
tmp
})
names(res) <- frame_list
list2env(res, envir = .GlobalEnv)
}
fun("^frame")

相关内容

最新更新