Skip to content
Prev 283073 / 398498 Next

extract fixed width fields from a string

On Sun, Jan 22, 2012 at 03:34:12PM -0500, Sam Steingold wrote:
Hi.

Here, you get the result only for the first string due
to "[[1]]" applied to strsplit(str,"").

As suggested by Michael, a matrix can be used, if
the input is a character vector, whose components
have the same character length (nchar).

  strings2int <- function (str, base=10) {
    m <- length(str)
    n <- unique(nchar(str))
    stopifnot(length(n) == 1) # test of all nchar() equal
    ch <- strsplit(str, "")
    ch <- unlist(ch)
    d <- matrix(digits[ch], nrow=m, ncol=n, byrow=TRUE)
    c(d %*% base^(n:1 - 1))
  }

  strings2int(c("100","012","213","453"))

  [1] 100  12 213 453

  strings2int(c("100","12","213","453"))

  Error: length(n) == 1 is not TRUE

Petr.