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]]

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to