Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 691
nachocab Avatar asked Jul 02 '13 13:07

nachocab


1 Answers

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.

like image 72
krlmlr Avatar answered Sep 21 '22 06:09

krlmlr