如何在R中给定位置生成给定变量字符的所有可能字符串?

编程入门 行业动态 更新时间:2024-10-07 16:23:05
本文介绍了如何在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中给定位置生成给定变量字符的所有可能字符串?

本文发布于:2023-11-30 07:33:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   变量   字符   位置   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!