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
|