如何使用R通过向量迭代或组合来构造输入字符串? [英] How do I construct an input string by iteration or combinations through a vector using R?

查看:0
本文介绍了如何使用R通过向量迭代或组合来构造输入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个字符串向量作为模型测试的输入(它最终进入lmer函数)。对于不同的测试,我必须对列进行大量更改,因此在一开始就将它们声明到一个位置来执行此操作将真正加快过程。

向量(字符串)由列标题(来自数据)组成。 当前有两个固定的起点,然后我想在不重复且顺序不重要的情况下迭代可用列选项。

示例输入:

first_col <- "SpA"
secondFixedcol <- "SpecB"
other_cols <- c("C", "D", "E", "F") #This can have any number of parameters

模型文本输出示例:

modelsText <- c('SpecB',
                'SpA + SpecB',
                'SpA + SpecB + C',
                'SpA + SpecB + D',
                'SpA + SpecB + E',
                'SpA + SpecB + F',
                    'SpA + SpecB',
                    'SpA + SpecB + C + D',
                    'SpA + SpecB + C + E',
                    'SpA + SpecB + C + F',
                        'SpA + SpecB + C + D + E',
                        'SpA + SpecB + C + D + F',
                            'SpA + SpecB + C + D + E + F')

我的大脑试图告诉我使用粘贴功能为循环构建某种形式的科学怪人(这在现阶段我仍然无法理解),但肯定有更优雅的使用矢量化?

我的另一个想法是使用combinations(4, 3, other_cols, repeats.allowed = FALSE)

然后使用嵌套的for循环遍历该循环?

推荐答案

灵感来源于this answer

combos = do.call(c, lapply(seq_along(other_cols), function(y) {
  arrangements::combinations(other_cols, y, layout = "l")
}))

formulas = sapply(combos, paste, collapse = " + ")

formulas = paste(first_col, secondFixedcol, formulas, sep = " + ")
formulas
#  [1] "SpA + SpecB + C"             "SpA + SpecB + D"             "SpA + SpecB + E"            
#  [4] "SpA + SpecB + F"             "SpA + SpecB + C + D"         "SpA + SpecB + C + E"        
#  [7] "SpA + SpecB + C + F"         "SpA + SpecB + D + E"         "SpA + SpecB + D + F"        
# [10] "SpA + SpecB + E + F"         "SpA + SpecB + C + D + E"     "SpA + SpecB + C + D + F"    
# [13] "SpA + SpecB + C + E + F"     "SpA + SpecB + D + E + F"     "SpA + SpecB + C + D + E + F"

我将留给您来添加不涉及任何other_cols的公式--只要在前面加上c()就可以了。

这篇关于如何使用R通过向量迭代或组合来构造输入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆