1

I'm trying to eval(parse()) variable names from a character vector, but eval() returns only the content of the last variable:

My code:

c <- c(1,1) a <- c(1,0) t <- c(0,1) g <- c(0,0) sequence <- c("a", "t", "g", "t", "g", "t", "a", "c") eval(parse(text=sequence)) 

It should return:

[1] 1 0 0 1 0 0 0 1 0 0 0 1 1 0 1 1

But it just returns the correspondent to the last element of the vector: c

[1] 1 1

2 Answers 2

1

We can use mget to get all the object values in a list, then unlist the list to create a vector

unlist(mget(sequence), use.names = FALSE) #[1] 1 0 0 1 0 0 0 1 0 0 0 1 1 0 1 1 

With eval(parse, it requires a length of 1. We can loop over the sequence and do the eval (not recommended)

c(sapply(sequence, function(x) eval(parse(text = x)))) #[1] 1 0 0 1 0 0 0 1 0 0 0 1 1 0 1 1 
Sign up to request clarification or add additional context in comments.

3 Comments

I definitely like the first way. I guess my question (more for the OP, not you) is whether the objects should simply be in a list() in the first place.
@Adam It is possible that the OP is new to R and when you are new, it is difficult to follow how the list works. So, they create objects in the global env.
@akrun is absolutely right! ;) @Adam the object is a vector in a list. It's the Value of the function readfasta from the package seqinr .
0

I realized that I can do it with:

bin <- NULL for(n in 1:length(sequence)) { bin <- append(bin, eval(parse(text=sequence[n]))) } 

But I wonder if is there an easier way to do it without the for loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.