Multiple variables to one with specified spaces: tidyr::unite() or something else?

a b c d e
1 2 3 900100 500
1 2 3 900200 0
4 5 6 500100 900
4 5 6 500200 0

I want to unite all the variables a:e, mutate a new variable desired:

  • unite a and b without any space
  • then unite with c with 1 space
  • then unite with d with 2 spaces
  • then unite with e with 3 spaces

Below is the desired output:

# A tibble: 4 x 1
  desired           
  <chr>             
1 12 3  900100   500
2 12 3  900200   0  
3 45 6  500100   900
4 45 6  500200   0  
library(tidyverse)
# toy data
df <- structure(list(a = c(1, 1, 4, 4), b = c(2, 2, 5, 5),
                     c = c(3, 3, 6, 6), d = c(900100, 900200, 500100, 500200),
                     e = c(500, 0, 900, 0)),
                class = c("tbl_df", "tbl", "data.frame"), 
                row.names = c(NA,-4L))
DF <- data.frame(
 a = c(1, 1, 4, 4), b = c(2, 2, 5, 5),
 c = c(3, 3, 6, 6), d = c(900100, 900200, 500100, 500200),
 e = c(500, 0, 900, 0)
)

make_pairs <- function(x) paste0(DF[,1:2][x,1],DF[,1:2][x,2])
v <- vector()
for(i in 1:4) v[i] = make_pairs(i)
DF$pair <- v
DF$d <- paste(" ",as.character(DF$d))
DF$all <- paste0(DF$pair," ",DF$c,DF$d,"   ",DF$e, sep = " ")
desired <- format(DF[7],justify = "left")
DF <- DF[,1:5]
desired
#>                   all
#> 1 12 3  900100   500 
#> 2 12 3  900200   0   
#> 3 45 6  500100   900 
#> 4 45 6  500200   0
1 Like

@technocrat thanks a lot!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.