Search code examples
rgetpastecbind

R cbind with get paste


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?


Solution

  • 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))))