[R] parse and eval character vector

Rob Foxall rfoxall27 at gmail.com
Tue Aug 26 10:36:15 CEST 2008


Dear R-help,

I have a character vector, some elements will be numeric, some not,
and some even empty. E.g.:

temp1 <- c("abcd","  2 ","")

I'm only interested in the numeric elements, the rest I can just throw
away. It is easy enough to loop through the vector:

temp <- try(eval(parse(text=temp1[1])), silent=TRUE); class(temp) # try-error
temp <- try(eval(parse(text=temp1[2])), silent=TRUE); class(temp) # numeric
temp <- try(eval(parse(text=temp1[3])), silent=TRUE); class(temp) # NULL

and then throw away the non-numeric/NULL stuff. But, as this vector
will be long, I would really like to speed things up by not using a
loop, and I thought that "lapply" might do the trick. However:

temp.fn <- function(x)
  try(eval(parse(text=x)), silent=TRUE)

temp2 <- lapply(temp1, FUN=temp.fn)
class(temp2[2]) # list, for elements 1, 2, and 3

and I don't know how to extract the numeric elements from here. So,
can I either use lapply as above and somehow get the information I
need out of "temp2" (I've tried using "unlist" but had no success), or
is there some other function that I can apply to my character vector
to avoid looping?

Rob.



More information about the R-help mailing list