[R] Converting a string vector with names to a numeric vector with names

Petr Savicky savicky at cs.cas.cz
Thu Mar 1 22:32:20 CET 2012


On Thu, Mar 01, 2012 at 03:28:31PM -0500, John C Nash wrote:
> Not paying close attention to detail, I entered the equivalent of
> 
> pstr<-c("b1=200", "b2=50", "b3=0.3")
> 
> when what I wanted was
> 
> pnum<-c(b1=200, b2=50, b3=0.3)
> 
> There was a list thread in 2010 that shows how to deal with un-named vectors, but the same
> lapply solution doesn't seem to work here i.e.,
> 
> pnum<-lapply(pstr, as.numeric)
> 
> or similar vapply version. The names and = signs seem to mess things up.
> 
> This is clearly not critical, but it would be nice to know an appropriate transformation.

Hi.

Try the following.

  mat <- sapply(strsplit(pstr, "="), identity)
  x <- as.numeric(mat[2, ])
  names(x) <- mat[1, ]
  x

     b1    b2    b3 
  200.0  50.0   0.3 
 
Hope this helps.

Petr Savicky.



More information about the R-help mailing list