问题
I'm trying o output the list names every time I run the function thru lapply
. I posted this question earlier that I posted earlier, and the answer provided by @Ananda Mahto worked fine until I upgraded my R
to version 3.2.0. It is no longer working and I get the following error message: Error in eval.parent(quote(names(X)))[substitute(x)[[3]]] : invalid subscript type 'symbol'
x <- ts(rnorm(40,5), start = c(1961, 1), frequency = 12)
y <- ts(rnorm(50,20), start = c(1971, 1), frequency = 12)
z <- ts(rnorm(50,39), start = c(1981, 1), frequency = 12)
a <- ts(rnorm(50,59), start = c(1991, 1), frequency = 12)
dat.list <- list(x=x,y=y,z=z,a=a)
abc <- function(x) {
r <- mean(x)
print(eval.parent(quote(names(X)))[substitute(x)[[3]]])
return(r)
}
forl <- lapply(dat.list, abc)
I'm not sure what the issues is, but I checked all the syntax in the new version of R
nothing has changed. Any help is greatly appreciated. I'm open to any new ideas as well.
回答1:
If you restructure it a little, you can get the same effect with a simpler appearance:
set.seed(42)
## using your dat.list construction code from above
abc <- function(x) { r <- mean(x); return(r); }
forl <- mapply(function(n, x) {
message(n)
abc(x)
}, names(dat.list), dat.list, SIMPLIFY=FALSE)
## x
## y
## z
## a
forl
## $x
## [1] 4.960464
## $y
## [1] 20.1141
## $z
## [1] 38.87175
## $a
## [1] 58.89825
I'm presuming you wanted the output in a list
vice a vector
, ergo SIMPLIFY=FALSE
to mimic lapply
. Otherwise, it's a simpler vector.
It's not as generic in that you have to explicitly pass the names as well as the dat, though you can create a sandwich function at the cost of having to reimplement lapply
functionality.
A personal coding preference I'm using here is the use of message
over print
. The rationale is that the user has the option to use suppressMessages
(outside the mapply
, assuming it could/would be buried in a function), whereas suppressing the output of a print
call is a bit more work.
来源:https://stackoverflow.com/questions/30330104/print-list-names-while-iterating-in-lapply-not-working-in-3-2