How to get rid of "" object name and working in loop?
I do not know how to precisely define this problem; but I could not figure this out
genx <- list(scaffold_1 = c("AAATTTTTATAT"),scaffold_2 = c("AAATTTTTATAT"),
scaffold_3 = c("AAATTTTTATAT"),scaffold_4 = c("AAATTTTTATAT"),
scaffold_5 = c("AAATTTTTATATA"),scaffold_6 = c("AAATTTTTATAT"),
scaffold_7 = c("AAATTTTTATAT"),scaffold_8 = c("AAATTTTTATATA"))
TATA = "TATA"
myobs <- paste("genx$scaffold_", 1:8, sep = "")
I want to apply the following function to every elments of the elements of myobs (are objects):
source("http://www.bioconductor.org/biocLite.R")
biocLite("Biostrings")
require((Biostrings)
countPattern (TATA, genx$scaffold_1, max.mismatch = 1)
[1] 3
When I use the following:
countPattern (TATA, myobs[1], max.mismatch = 1)
Doesnot work as it is I believe interpreted as:
countPattern (TATA, "genx$scaffold_1", max.mismatch = 1)
[1] 0
Which is not same as the above one. How can get开发者_如何学编程 rid of "" and create a loop to perform this job, your suggestions are appreciated:
You can directly use the list and do an sapply
which acts on every element of the list. Here is some sample code
sapply(genx, countPattern, pattern = TATA, max.mismatch = 1)
You can use the get
function
a <- 12
get("a") # returns 12
What about this:
sapply(genx, function (x) { countPattern(TATA, x, max.mismatch = 1) })
There is a problem with:
get("genx$scaffold_1")
because R thinks you are looking for an object with that full name, not the 'scaffold_1' component of 'genx'.
What should work is:
eval(parse(text="genx$scaffold_1"))
But see:
fortune(106)
More trouble spots along these lines can be found in 'The R Inferno': http://www.burns-stat.com/pages/Tutor/R_inferno.pdf
I would recommend that you define genx$scaffold
as vector, and then you can easily use the apply function:
genx = data.frame(scaffold = c(1, 2, 3, 4)) # genx$scaffold is a vector
Now you can easily run the countPattern()
function on every genx$scaffold's element
apply(as.matrix(genx$scaffold), 1,
function (x) { countPattern(TATA, x, max.mismatch = 1) })
You can easily extend the solution so that genx$scaffold can be also matrix etc.
精彩评论