Is there a way to give the list
which is return from lapply
names within the function or is it only possible afterwards?
base function: lapply(1:2, function(x) x^2)
Wrapper function:
lapply2 <- function(X, FUN, names, ...) {
xxx <- lapply(X, FUN, ...)
names(xxx) <- names
return(xxx)
}
lapply2(1:2, function(x) x^2, c("a", "b"))
This wrapper function works, but somehow I don't think this is the most elegant way.
1 Like
I found an old example of lapply
which was apparantly written in R and not in C.
la1 <- function(X, FUN, ...) {
FUN <- match.fun(FUN)
if (!is.list(X))
X <- as.list(X)
rval <- vector("list", length(X))
for(i in seq(along = X))
rval[i] <- list(FUN(X[[i]], ...))
names(rval) <- names(X) # keep `names' !
return(rval)
}
Thus, even if a package or function exists, you can't get better than following
lapply2 <- function (X, FUN, ...) {
names <- names(X)
FUN <- match.fun(FUN)
if (!is.vector(X) || is.object(X)) {
X <- as.list(X)
}
names(X) <- names
.Internal(lapply(X, FUN))
}
It would be nice though to know why the names were dropped in the first place.
system
Closed
3
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.