user8853874
user8853874

Reputation:

how to use for loop to create a data frame?

I made 150 vectors and I called them c1,c2,...,c150 now I want to make a dataframe with them. is there a easy way to not write 150 vectors by hand like this:

  data<-data.frame(c1,c2,c3,...,c150)

writing 150 vectors in the above bracket is frustrating

Upvotes: 0

Views: 63

Answers (2)

akrun
akrun

Reputation: 886938

We can use

data.frame(mget(paste0("c", 1:150)))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388807

Use mget to get all the vectors in a list and then wrap it in data.frame

data.frame(mget(ls(pattern = "c\\d+")))

#   c1 c2
#1   1 11
#2   2 12
#3   3 13
#4   4 14
#5   5 15
#6   6 16
#7   7 17
#8   8 18
#9   9 19
#10 10 20

data

c1 <- 1:10
c2 <- 11:20

Upvotes: 3

Related Questions