[R] MApply and SubStr

Brian Trautman btrautman84 at gmail.com
Wed Feb 11 00:58:13 CET 2015


Hi!

I'm trying to write a custom function that applies SubStr to a string, and
then depending on the arguments, converts the output to a number.

The substring part of my code works fine, but it's not converting the way I
want to --

options('stringsAsFactors'=FALSE)
require(data.table)

substr_typeswitch <- function(x, start, stop, typeto='chr')
{
  tmpvar <- substr(x=x, start=start, stop=stop)
  tmpvar <- switch(typeto, num=as.numeric(tmpvar), tmpvar)
  return(tmpvar)
}
  startpos <- c(01, 03)
  endpos <-   c(02, 04)
  typelist <- c('chr', 'num')

  startdata <- as.data.table(c('aa01', 'bb02'))

  enddata_want <- as.data.table(mapply(substr_typeswitch, startdata,
startpos, endpos, typelist))

If I examine enddata_want --

> str(enddata_want)
Classes ‘data.table’ and 'data.frame': 2 obs. of  2 variables:
 $ V1: chr  "aa" "bb"
 $ NA: chr  "1" "2"
 - attr(*, ".internal.selfref")=<externalptr>

"1" and "2" are being stored as character, and not as number.

Can anyone help me understand what I'm doing wrong?

Thank you!

	[[alternative HTML version deleted]]



More information about the R-help mailing list