What Does C Do in R? [Duplicate]

What Does C Do in R? [Duplicate]

Consider the code below:

k <- c(.5, 1)

What does c do here? I think it must be a list or vector. If it is, how can I extend this vector to contain 1024 values?

7

2 Answers

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

In your example:

k <- c(0.5, 1) # k is a vector
k[1] # is 0.5 (remember, R indices start on 1)
k[2] # is 1

If you want to create a vector with 1024 entries (assuming 0.5 increments), you have at least two ways to do it:

# One way
k <- (1:1024) / 2 # this will be 0.5, 1, 1.5, 2, ... , 512
# Another way:
k <- seq(0.5, 512, 0.5)

Also you can use c() to concatenate two vectors:

k <- c(0.5, 1)         # k = 0.5, 1
k <- c(k, 1.5)         # k = 0.5, 1, 1.5
k <- c(k, c(2, 2.5))   # k = 0.5, 1, 1.5, 2, 2.5
k <- c(k, k)           # k = 0.5, 1, 1.5, 2, 2.5, 0.5, 1, 1.5, 2, 2.5

Please check the help for c() and seq function (in R: ?c and ?seq)


Reference:

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

gives you a vector with 1024 values.


The built-in help in R is pretty good for questions like this. Just type ?functionName in your R terminal to get help on any function loaded in your environment.

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.