0

I'm trying to write a function in R that returns a matrix of k columns, where k is a function argument.

The columns are formed inside the function by a loop and I have used (assign(paste ), i) to name them col.1,...,col.i. So far so good, and the code works to generate the column vectors correctly.

Already defined in the function are vectors, col.2 to col.k. X is also defined as equal to col.1.

I have then tried to use a loop within the function, to cbind() the columns, as follows:

for (i in 2:k){
X <- cbind(X, col.i)
}

The error message is "object 'col.i' not found".

I don't have much experience of coding, so it's probably a beginner's mistake, but I'd be grateful for any suggestions.

  • How about `X <- cbind(X, get(col.i))` – ThomasIsCoding Dec 06 '19 at 07:19
  • I m not sure what you are trying to do but this does not seem to be the correct way. As far as your loop goes, the most obvious mistake is the `cbind(X, col.i)` which must be `cbind(X, paste0('col.', i))` – Sotos Dec 06 '19 at 07:19
  • 4
    Quick solution: `get(paste0('col.', i))`, however, your approach to this problem should be reconsidered -- cluttering your namespace with `col.1`, `col.2`, ... objects is not great. Even keeping them in a list like `list(col.1, col.2, col.3)` would allow you to just extract `l[[i]]` (much cleaner already) – MichaelChirico Dec 06 '19 at 07:20
  • 2
    See also: https://stackoverflow.com/questions/17559390/why-is-using-assign-bad – MichaelChirico Dec 06 '19 at 07:21
  • Thank you for the comments, but I haven't been able to fix the problem. Can I put it another way? Given a set of k vectors, defined and named within a function, where k is a function argument, how do you create a matrix from those vectors? – James McNicholas Dec 06 '19 at 07:32
  • When generating the columns, store them in a list e.g. by calling the function in lapply . Then your task will be easy to achieve and programmatically more elegant. – Michael M Dec 06 '19 at 08:09

1 Answers1

1

Try

df <- do.call(rbind, mget(paste0('col', 1:k)))

Or with dplyr and data.table packages

df <- dplyr::bind_rows(mget(paste0('col', 1:k)))

df <- data.table::rbindlist(mget(paste0('col', 1:k)))

This will return all the vectors from col1 to colk as columns in the dataframe df.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213