s-news
[Top] [All Lists]

Re: string of digits to vector of integers

To: "Knut M. Wittkowski" <kmw@rockefeller.edu>
Subject: Re: string of digits to vector of integers
From: Sundar Dorai-Raj <sundar.dorai-raj@pdf.com>
Date: Mon, 26 May 2003 08:39:18 -0500
Cc: s-news@lists.biostat.wustl.edu
Organization: PDF Solutions, Inc.
References: <5.1.0.14.0.20030524201937.02563a48@imap.rockefeller.edu>
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.0.2) Gecko/20021120 Netscape/7.01


Knut M. Wittkowski wrote:
I'm trying to "unpaste" a string of digits into a vector of integers (see my earlier mail). The statement sapply(...) below works when I test it, but when it is put into a function, it doesn't.

Any explanation?

Knut

-----------------

Dgts2Int <- function(Dgts)
{
        sapply(1:nchar(Dgts),
                function(i)
                        as.integer(substring(Dgts,i,i)))
}

DgtsRw <- "11011"

sapply(1:nchar(DgtsRw),
        function(i)
                as.integer(substring(DgtsRw,i,i)))

#
# result is:
#
# [1] 1 1 0 1 1
#
# - ok
#

Dgts2Int(DgtsRw)

#
# result is:
#
# Problem in FUN(...X.sub.i....): Object "Dgts" not found
# Use traceback() to see the call stack
#

scoping problem. Try this:

sapply(1:nchar(Dgts),
       function(i, d) as.integer(substring(d, i, i)),
       d = Dgts)

However, substring is vectorized, so sapply isn't really needed:

> Dgts <- "001110"
> as.integer(substring(Dgts, 1:nchar(Dgts), 1:nchar(Dgts)))
[1] 0 0 1 1 1 0

Regards,
Sundar


<Prev in Thread] Current Thread [Next in Thread>