Cannot unlist a list coerced from a call object in R? -
here experiment:
myfunc = function(a, b, c) { callobj = match.call() save(callobj, file="/tmp/callobj.rda") } myfunc(11, 22, 33) load("/tmp/callobj.rda") x = unlist(as.list(callobj)) print(x) x = unlist(list(a = 1, b = 2, c = 3)) print(x)
results:
> myfunc(11, 22, 33) > load("/tmp/callobj.rda") > x = unlist(as.list(callobj)) > print(x) [[1]] myfunc $a [1] 11 $b [1] 22 $c [1] 33 > x = unlist(list(a = 1, b = 2, c = 3)) > print(x) b c 1 2 3
the question is, why on earth 2 lists behave differently? 1 of them can unlisted, other, apparently, cannot.
as suggested in 1 of comments, did this:
> dput(as.list(callobj)) structure(list(myfunc, = 11, b = 22, c = 33), .names = c("", "a", "b", "c")) > dput(list(a = 1, b = 2)) structure(list(a = 1, b = 2), .names = c("a", "b"))
doesn't explain why 2 lists different in behavior.
you can use as.character
on call
objects.
this equivalent unlisted, unnamed call as.list(callobj)
.
> as.character(callobj) # [1] "myfunc" "11" "22" "33"
to unlist callobj
, need elements of same type. can't have characters, numerics, , calls in same vector. r not allow mixed object types in same vector.
but can use deparse
, done:
> sapply(as.list(callobj), deparse) # b c # "myfunc" "11" "22" "33"
this makes apparent 1 of main differences between sapply
, lapply
. don't need unlist
if use sapply
.
Comments
Post a Comment