I have a dataset that looks something like this.
site <- c("A", "B", "C", "D", "E") D01_1 <- c(1, 0, 0, 0, 1) D01_2 <- c(1, 1, 0, 1, 1) D02_1 <- c(1, 0, 1, 0, 1) D02_2 <- c(0, 1, 0, 0, 1) D03_1 <- c(1, 1, 0, 0, 0) D03_2 <- c(0, 1, 0, 0, 1) df <- data.frame(site, D01_1, D01_2, D02_1, D02_2, D03_1, D03_2)
I am trying to combine columns D0x_1 and D0x_2 so that the values ββin the columns are separated by a slash. I can do this with the following code, and it works fine:
library(dplyr) library(tidyr) df.unite <- df %>% unite(D01, D01_1, D01_2, sep = "/", remove = TRUE) %>% unite(D02, D02_1, D02_2, sep = "/", remove = TRUE) %>% unite(D03, D03_1, D03_2, sep = "/", remove = TRUE)
... but the problem is that this requires me to enter a couple of unite several times, and it is cumbersome for the large number of columns in my dataset. Is there a way in dplyr join through the same patterned column names and then cross the columns? unite_each does not seem to exist.