Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between 1:10 and c(1:10)

Tags:

r

rstudio

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"
like image 358
IAMTubby Avatar asked Dec 15 '14 14:12

IAMTubby


People also ask

What is C () R?

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.

How do you write a sequence in R?

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).


1 Answers

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.
like image 156
zipp Avatar answered Sep 28 '22 04:09

zipp