How to distinguish between an element and a vector of length 1 in R?

r

Solution

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.

Problem

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?

Original source