Tom Tom - 1 month ago 6
R Question

How to connect multiple variables into one vector

I have variables from

c1
to
c24
, totally 24 variables. I want to do something like:

b <- c(c1,c2,c3,c4,c5,c6,c7,c8,c9,
c10,c11,c12,c13,c14,c15,c16,c17,
c18,c19,c20,c21,c22,c23,c24)


How could I do this ? It is not working to use something like
b <- c(c 1:c24)
, R only connects two values (
c1
and
c24
) in this case, but I want to put all 24 values into this vector.

Answer

You can do this with lapply and get:

c1 <- c2 <- c3 <- c4 <- 1
unlist(                   ## convert from list to vector
    lapply(               
        paste0("c",1:4),  ## names of variables
        get)              ## retrieve variable by name
)
## [1] 1 1 1 1

In general, it would be a good idea to look further back in your workflow and see if it's possible to generate those variables within a list in the first place ...