John L
John L

Reputation: 49

Writing a function to include gsub for input and outputs a substring

Using this string:

dna_string
[1] "ACCTGTCATCATCCCGCTCGCTTA"

I am trying to write a function that will replace "T" with "U" and output the result as triplets, e.g. "ACC" "TGT" and so on.

The function I have started to write is:

dna_converter <- function(gsub("T", "U", x=dna_string)){
  rna_triplets <- substring(dna_string, seq(1, 22, 3), seq(3, 24, 3))
  return(rna_triplets)
}

I am getting an error and R will not output the results as desired. Please could you advise where I might be going wrong here?

Upvotes: 0

Views: 80

Answers (2)

Matt W.
Matt W.

Reputation: 3722

You’re trying to put the body of the function as the function argument. Functions are defined as

Find <- function(argument){
       Body
      }

Try:

dna_converter <- function(input_string){
gsub("T", "U", x=input_string)
rna_triplets<-substring(input_string, seq(1, 22, 3), seq(3, 24, 3))
return(rna_triplets)
}

Triplets <- dna_converter(dna_string)

The substring argument should be cleaned up to not specify a specific length and just cut into pieces of 3 but I’m on my phone and can’t try it out in R. Will clean up this answer later!

Upvotes: 0

pogibas
pogibas

Reputation: 28369

Specification of your function arguments is weird - this is how I would do it:

dna_string <- "ACCTGTCATCATCCCGCTCGCTTA"
dna_converter <- function(x = dna_string, From = "T", To = "U", By = 3) {
    foo <- nchar(x)
    substring(gsub(From, To, x), 
              seq(1, foo - 1, By), 
              seq(By, foo, By))
}   
dna_converter()
[1] "ACC" "UGU" "CAU" "CAU" "CCC" "GCU" "CGC" "UUA"

Upvotes: 1

Related Questions