c() in R: How to Create Vector using c() Function

To create a vector in R, use the c() function. The c() function is S4 generic but with an argument list (x, …). The c() function can be used to combine two vectors.

c() in R

The c() is a built-in R generic function that combines its arguments. The c() function creates a vector explicitly providing values. The default method combines its arguments to form a vector. All arguments are coerced to a common type of the returned value, and all attributes except names are removed.

The c() in R stands for “combine”. The c() function returns the output by giving parameters inside the function. The parameters are of the format c(row, column).

With the c function, you can extract data in three ways:

  1. To get only rows, use the c(row, ) function.
  2. To get only columns, use the c(, column) function.
  3. To get the rows and columns together, use the c(row, column) function.

Syntax

c(…, recursive = FALSE, use.names = TRUE)

Parameters

…: They are the objects to be concatenated.
recursive: It is logical. If recursive = TRUE, the function recursively descends through lists (and pairlists), combining all their elements into a vector.
use.names: It is a logical argument indicating if names should be preserved.

Return Value

The c() function returns NULL, an expression, or a vector of an appropriate mode.

Example

In R, the c() function returns a vector.

rv <- c(19, 21)
rv
rv[1]
rv[2]

Output

[1] 19 21
[1] 19
[1] 21

If you want to create a vector with 11 entries, use the following function.

data <- (1:11)
print(data)

Output

 [1] 1 2 3 4 5 6 7 8 9 10 11

Concatenate two vectors using c() function

To concatenate two vectors in R, use the c() function.

p <- c(1, 1)
p <- c(1, 5)
p <- c(p, c(1, 1.5))
p <- c(p, p)
print(p)

Output

[1] 1.0 5.0 1.0 1.5 1.0 5.0 1.0 1.5

You can see that the output is a combined vector.

To combine values into a vector or list, use the c() function.

That is it for the c() function in R.

Leave a Comment