J. Mini
J. Mini

Reputation: 1610

How to unlist a list of mixed types without losing those types?

Suppose that you have a list of mixed types, say list("Alice",64,c(11L,12L)) and you want to unlist these, to get something like "Alice", 64 , c(11L,12L) as your output. R's unlist is inadequate for this because it will coerce all of your inputs in to strings and therefore output "Alice" "64" "11" "12".

I know of a few hacks for fixing this problem when your type are not mixed, but what can be done in a mixed-type case like this? If this is not possible with a list, is there a more general "list" type that could be used instead?

Edit: Comments have rightly pointed out that having "something like "Alice", 64 , c(11L,12L) as your output" is the whole point of the list type. However, I want these outputted to the terminal, rather than outputted as a single object that stores all of these items. Is this possible?

Upvotes: 0

Views: 188

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24790

If you just want to print the elements, you could use lapply and dput:

invisible(lapply(list("Alice",c(11L,12L),64,c(11,13,12),list(A = 2,B = 3)), dput))
#"Alice"
#11:12
#64
#c(11, 13, 12)
#list(A = 2, B = 3)

Upvotes: 2

Related Questions