I understand that c is used to combine elements. But what is the difference between 1:10 and c(1:10)? I see that the outputs are the same. Shouldn't c(1:10) give an error, because 1:10 already combines all the elements?
> 1:10
[1] 1 2 3 4 5 6 7 8 9 10
> c(1:10)
[1] 1 2 3 4 5 6 7 8 9 10
> class(1:10)
[1] "integer"
> class(c(1:10))
[1] "integer"
The c function in R is used to create a vector with values you provide explicitly. If you want a sequence of values you can use the : operator. For example, k <- 1:1024.
The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works. That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).
If you combine (aka c
function) with only one parameter it is the same as the identity (aka not calling the c
function). Therefore c(1:10)
is the same as 1:10
. However you can combine with as many arguments as you want with different type (character,number...). It will convert the type for you.
all.equal(1:10,c(1:5,6:10))
[1] TRUE
all.equal("meow",c("meow"))
[1] TRUE
c(1:5,6:10,"meow")
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "meow"
class(c(1:5,6:10,"meow"))
[1] "character"
Another difference is that you can call c with the parameter recursive. As the doc states:
?c
Usage
c(..., recursive = FALSE)
Arguments
...
objects to be concatenated.
recursive
logical. If recursive = TRUE, the function recursively descends through lists (and pairlists) combining all their elements into a vector.
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