0

cbind() function works as x <- cbind(a,b)

where column name 'b' can be specified for the function b = get(paste0('var',i)),

that is x <- cbind(a,b = get(paste0('var',i)))

I am trying to do the following:

x <- cbind(a, get(paste0('var',i))) = j), where "j" can be a vector or a function.

however, got the following error: Error: unexpected '=' in "x <- cbind(a, get(paste0('var',i))) = j)"

If i just specify "x <- cbind(a, get(paste0('var',i))))", then the 2nd column name is "get(paste0('var',i))))", which is not convenient.

How can I define column names with a function get(paste()) within cbind() or rbind() or bind_cols()? Or what would be the alternative solution?

Gregory
  • 109
  • 1
  • 7

2 Answers2

1

An example would have been helpful to understand the problem but maybe this?

x <- cbind(a, j)
colnames(x)[2] <- get(paste0('var',i))

Or if you want to do it in single line -

x <- cbind(a, setNames(j, get(paste0('var',i))))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • That would work, but in my case the 'j' is dynamic vector, therefore, it is the same problem. – Gregory Aug 10 '21 at 13:45
  • Can you provide an example? – Ronak Shah Aug 10 '21 at 13:53
  • Unfortunately I cannot, because I work on the remote server with a set of many csv files. The point is: I would like to make a new calculated variable (column) for each of the data frames, that is conditional on dataframe name, and bind it to each data frame, therefore, I am trying to 'paste' the specific name to the cbind() function. – Gregory Aug 10 '21 at 14:02
  • So far came with this solution: `assign('a', function())` `assign('b', function())` `X <- cbind(a, b)` `colnames(x)[ncol(x)] <- paste0('var',i)` `assign(paste0('x',i), x)` – Gregory Aug 10 '21 at 19:29
0

We can use

x <- data.frame(a, j)
colnames(x)[2] <- get(paste('var', i, sep=""))

Or use tibble

tibble(a, !! b := j)
akrun
  • 874,273
  • 37
  • 540
  • 662