Search code examples
rcopydplyrmultiple-columnsprefix

Copy a column and add a prefix to new column in R with dplyr


Does someone know how to copy a column in a data.frame and add a prefix to the new column?

The idea is to have a character vector containing certain column names of a dataframe and to copy these with a prefix to subsequently perform an action upon.

The reason is that I want to use the spread function on these columns, but as far as I know the spread function does not preserve the original column. What I would like:

From a data.frame with the following column names:

column_names <- c('var1', 'var2', 'var3')

To a dataframe with the following columns

column_names <- c('var1', 'var2', 'var3', 'prefix_var1','prefix_var3')

Where the columns with 'prefix' contain the same data as their orginal columns.

What I've tried so far, which partially succeeded:

sel_columns <- c('var1', 'var3')

data <- data.frame(var1 = c(12,3,4), var2 = c(123,5435,121), var3 = c(23,456,123))

new_data <- data %>% mutate_at(one_of(sel_columns), funs(.))
#Error in eval(substitute(expr), envir, enclos) : 
#  could not find function "var1"
#In addition: Warning message:
#In one_of(sel_columns) : Unknown variables: `var1`, `var3`


new_data2 <- data %>% select(one_of(sel_columns)) %>% mutate_all(funs(prefix = . * 1)) %>% c(data, .) %>% data.frame

Solution

  • We can try this in base R

    cbind(data, setNames(data[sel_columns], paste0("prefix_", sel_columns)))
    
    #  var1 var2 var3 prefix_var1 prefix_var3
    #1   12  123   23          12          23
    #2    3 5435  456           3         456
    #3    4  121  123           4         123