So, I know that I can use the data.frame command to combine multiple vectors into one dataframe, like so:
my.data <- data.frame(name1, age1, name20, age20, name38, age38)
(I know, the variable names don't make much sense, why would I want name1, name20 and name38 in three different columns? Please ignore that: my actual variable names are different -- this is only for illustration purposes).
Problem is, I have about 40 of such vectors, and I have to combine many vectors in other parts of my code as well. So it would be convenient for me not to copy-paste a huge chunk of code every time. So I thought of writing a for loop around this:
for (i in c("name", "age", "hgt"))
{
for (k in c(1,20,38))
{
my.data$i,as.character(k) <- data.frame(get(paste(i,as.character(k),sep="")))
}
}
But this doesn't work. Is this because I should write "paste()" around some of this code, or is this simply a bad way to approach this problem? What is the correct way to loop through i and k and get a "newdata" dataframe as the final result with all the vectors as columns attached?