Force implicit conversion to most general shared class?

Viewed 19

Is there a function to force implicit conversion rules onto a heterogeneous list in order to convert it to an atomic vector of the most general shared class? For example, if I have list("apple", 12, TRUE), how can I turn this into c("apple", "12", "TRUE")?

1 Answers

R's class hierarchy roughly is logical < factor < integer < numeric < character. So unlist whch coerces into character should help, then list again to get list format.

list(unlist(list("apple", 12, TRUE)))
# [[1]]
# [1] "apple" "12"    "TRUE" 

If we have a nested list, we can create a "relistable" object which inherits from "list" and use relist after unlist:

l <- as.relistable(list("apple", list(12), TRUE))
relist(unlist(l))
# [[1]]
# [1] "apple"
# 
# [[2]]
# [[2]][[1]]
# [1] "12"
# 
# 
# [[3]]
# [1] "TRUE"
Related