Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

paste()ing columns whose names are stored in a variable

How do I create a new column from columns whose names are contained in a character vector?

Given these two variables:

data <- tibble(numbers = 1:10, letters = letters[1:10])
columns <- c("numbers","letters")

What command would produce this output?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# A tibble: 10 x 3
   numbers letters combined
     <int> <chr>   <chr>   
 1       1 a       1-a     
 2       2 b       2-b     
 3       3 c       3-c     
 4       4 d       4-d     
 5       5 e       5-e     
 6       6 f       6-f     
 7       7 g       7-g     
 8       8 h       8-h     
 9       9 i       9-i     
10      10 j       10-j  

My first thought was mutate(data, combined = paste(!!columns, sep = "-")) but this does not work.

Error: Problem with `mutate()` input `combined`.
x Input `combined` can't be recycled to size 10.
ℹ Input `combined` is `paste(c("numbers", "letters"))`.
ℹ Input `combined` must be size 10 or 1, not 2.

>Solution :

A tidyverse approach is to use unite, where you can pass the columns vector directly into the function without having to use !!.

library(tidyverse)

data %>% 
  unite("combined", columns, sep = "-", remove = FALSE) %>% 
  relocate(combined, .after = last_col())

Output

   numbers letters combined
     <int> <chr>   <chr>   
 1       1 a       1-a     
 2       2 b       2-b     
 3       3 c       3-c     
 4       4 d       4-d     
 5       5 e       5-e     
 6       6 f       6-f     
 7       7 g       7-g     
 8       8 h       8-h     
 9       9 i       9-i     
10      10 j       10-j 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading