Is there a way to distinguish between 1
and c(1)
? Apparently in R
c(1) == 1 # TRUE
as.matrix(c(1)) == 1 # TRUE
as.array(c(1)) == 1 # TRUE
which is a problem, for example, if I'm converting a vector to JSON:
library(rjson)
toJSON(c(1,2)) # "[1,2]"
toJSON(c(1)) # "1" instead of "[1]"
Any ideas?
It works as expected if you pass a list:
> toJSON(list(1))
[1] "[1]"
You can convert with as.list
:
> toJSON(as.list(c(1)))
[1] "[1]"
> toJSON(as.list(c(1, 2)))
[1] "[1,2]"
As noted in the other answers, there is no distinction between an atomic value and a vector of length one in R -- unlike with lists, which always have a length and can contain arbitrary objects, not necessarily of the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With