-1

How can I assign a letter into a number using Rstudio for example if A=1 C=2 G=3 T=4 ^= 5 !=6

zephryl
  • 14,633
  • 3
  • 11
  • 30
Mo19na
  • 25
  • 2
  • 2
    Sorry, your code is not clear. what is `^=5` – akrun Oct 24 '22 at 19:29
  • it's a character because I have a compressed sequence from burrows wheeler transform (BWT) so am trying to decoding. the compressed sequence is !^GATTACA – Mo19na Oct 24 '22 at 19:35
  • it's a character because I have a compressed sequence from burrows wheeler transform (BWT) so am trying to decoding. the compressed sequence is !^GATTACA. So when I use sort in R it puts the "^","!" at the beginning where I need it to be sorted at the end. so I thought assigning it to a numbers where I sort it the way I want – Mo19na Oct 24 '22 at 19:41
  • 4
    Welcome to SO! Please read https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example to learn how to write a better question, so that we can help you with your problem. – Ricardo Semião e Castro Oct 24 '22 at 19:43
  • am new in using this program, please can you help me am straggling a lot – Mo19na Oct 24 '22 at 19:44
  • Try ```x <- c(A=1, C=2, G=3, T=4, `^`= 5, `!`=6)```. Note the backticks in the special characters. – Rui Barradas Oct 24 '22 at 19:50
  • 2
    We're trying to help you ask a clear question. We can't help you with your question right now because we can't understand it. Please read Ricardo's link, and edit your question with the recommendations there. – Gregor Thomas Oct 24 '22 at 19:50

3 Answers3

4

in base R: use the function chartr

x = "!^GATTACA"
chartr('ACGT^!', '123456', x)
[1] "653144121"
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

As it's been pointed out in the coments, you need to give more context of your problem. In what format are your inputs and what is the expected output? See the link in the coments to lear how to improve.

But, assuming that you have a string saved onto a variable like:

x = "!^GATTACA"

You can replace each character using the str_replace_all of the stringr package:

install.packages("stringr") #if you don't have it installed yet
library(stringr)

str_replace_all(x, c("A"="1", "C"="2", "G"="3", "T"="4", "\\^"="5", "\\!"="6"))
0

I believe that one of the following is what is asked for.

x <- c(A=1, C=2, G=3, T=4, `^`= 5, `!`=6)
x
#> A C G T ^ ! 
#> 1 2 3 4 5 6

y <- "!^GATTACA"
s <- strsplit(y, "")[[1]]
i <- match(s, names(x))
i
#> [1] 6 5 3 1 4 4 1 2 1

s[c(3:length(s), 1, 2)]
#> [1] "G" "A" "T" "T" "A" "C" "A" "!" "^"

paste(s[c(3:length(s), 1, 2)], collapse = "")
#> [1] "GATTACA!^"

Created on 2022-10-24 with reprex v2.0.2

Note that if you sort the letters or indices you will loose the string "GATTACA".

sort(x[i])
#> A A A C G T T ^ ! 
#> 1 1 1 2 3 4 4 5 6

names(sort(x[i]))
#> [1] "A" "A" "A" "C" "G" "T" "T" "^" "!"

Created on 2022-10-24 with reprex v2.0.2

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66