如何在R中给定位置生成给定变量字符的所有可能字符串? [英] How to generate all possible strings given variable characters at given locations in R?

查看:53
本文介绍了如何在R中给定位置生成给定变量字符的所有可能字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个有序的字符串向量,其中每个字符串在该位置显示可能的字符,我如何获得所有可能的字符串组合?

Given an ordered vector of strings where each string shows the possible characters in that position, how can I get all possible combinations of strings?

例如,给定向量:

vec <- c("A", "A", "T", "C", "AG", "ACG", "T", "A", "A")

在给定位置5的情况下,可能的字符串组合可以是"A",也可以是"A".或"G",并且6可以是"A","C"或"G".是:

The possible string combinations, given positions 5 can be either "A" or "G", and 6 can be "A", "C", or "G" are:

strings <- c("AATCAATAA"
             "AATCACTAA"
             "AATCAGTAA"
             "AATCGATAA"
             "AATCGCTAA"
             "AATCGGTAA")

推荐答案

将向量分割成各个字符,然后使用 expand.grid():

Split your vector into individual characters, then use expand.grid():

vec <- c("A", "A", "T", "C", "AG", "ACG", "T", "A", "A")

strings <- expand.grid(strsplit(vec, ""), stringsAsFactors = FALSE)
strings
#>   Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9
#> 1    A    A    T    C    A    A    T    A    A
#> 2    A    A    T    C    G    A    T    A    A
#> 3    A    A    T    C    A    C    T    A    A
#> 4    A    A    T    C    G    C    T    A    A
#> 5    A    A    T    C    A    G    T    A    A
#> 6    A    A    T    C    G    G    T    A    A

这为我们提供了一个数据框,但是我们可以将这些行粘贴在一起以获得单个矢量:

This gives us a data frame, but we can paste the rows together to get a single vector:

apply(strings, 1, paste0, collapse = "")
#> [1] "AATCAATAA" "AATCGATAA" "AATCACTAA" "AATCGCTAA" "AATCAGTAA" "AATCGGTAA"

这篇关于如何在R中给定位置生成给定变量字符的所有可能字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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