An Introduction to the c() Function in R


You can use the c() function in R to perform three common tasks:

1. Create a vector.

2. Concatenate multiple vectors.

3. Create columns in a data frame.

This function uses the following basic syntax:

my_vector <- c(value1, value2, value3, ...)

Note that c() stands for “combine” because it is used to combine several values or objects into one.

The following examples show how to use this function in practice.

Example 1: Use c() to Create a Vector

The following code shows how to use c() to create a numeric vector:

#create numeric vector
numeric_vector <- c(4, 7565, 15, 93.22, 100, 50, 0)

#display numeric vector
numeric_vector 

[1]    4.00 7565.00   15.00   93.22  100.00   50.00    0.00

We can also use c() to create a character vector:

#create character vector
char_vector <- c('A', 'C', 'L', 'M', 'O')

#display character vector
char_vector 

[1] "A" "C" "L" "M" "O"

Example 2: Use c() to Concatenate Multiple Vectors

The following code shows how to use c() to concatenate multiple vectors into one:

#define two vectors
vec1 <- c(4, 15, 19, 18)
vec2 <- c(10, 100, 40, 20, 80, 85)

#concatenate vectors into one
vec3 <- c(vec1, vec2)

#view concatenated vector
vec3

[1]   4  15  19  18  10 100  40  20  80  85

Example 3: Use c() to Create Columns in a Data Frame

The following code shows how to use c() to create columns in a data frame in R:

#create data frame with three columns
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34))	

#view data frame
df

  team points assists
1    A     99      33
2    B     90      28
3    C     86      31
4    D     88      39
5    E     95      34

The result is a data frame with three columns, each created by using the c() function.

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use paste & paste0 Functions in R
How to Use the replace() Function in R
How to Use the View() Function in R
How to Use rep() Function in R

Leave a Reply

Your email address will not be published.