In this section, we’ll discuss a couple of miscellaneous facts related to the concatenate function, c()
, that often come in handy.
If the arguments you pass to c()
are of differing modes, they will be reduced to a type that is the lowest common denominator, as follows:
> c(5,2,"abc") [1] "5" "2" "abc" > c(5,2,list(a=1,b=4)) [[1]] [1] 5 [[2]] [1] 2 $a [1] 1 $b [1] 4
In the first example, we are mixing integer and character modes, a combination that R chooses to reduce to the latter mode. In the second example, R considers the list mode to be of lower precedence in mixed expressions. We’ll discuss this further in Section 4.3.
You probably will not wish to write code that makes such combinations, but you may encounter code in which this occurs, so it’s important to understand the effect.
Another point to keep in mind is that c()
has a flattening effect for vectors, as in this example:
> c(5,2,c(1.5,6)) [1] 5.0 2.0 1.5 6.0
Those familiar with other languages, such as Python, may have expected the preceding code to produce a two-level object. That doesn’t occur with R vectors though you can have two-level lists, as you’ll see in Chapter 4.
In the next chapter, we move on to a very important special case of vectors, that of matrices and arrays.