Home > database >  Paste multiple columns together and numbering
Paste multiple columns together and numbering

Time:04-11

Data

row1=c("A","B","C")
row2=c("D","E",NA)
df=data.frame(rbind(row1,row2))
df
     X1 X2 X3
row1  A  B  C
row2  D  E  NA

I want to 2row & 1col data frame, and the type of data is character

for example,

"1. A - 2. B - 3. C"
"1. D - 2. E"

Is there any other way other than using a loop?

I saw tidyr::unite, do.call, sprintf, ... But it's hard to apply in my case.

The dimensions of the actual data are larger. Actual data has more than 10 columns.

CodePudding user response:

We could do it this way:

library(tidyverse)

df %>% 
  mutate(across(starts_with("X"), ~ paste0(parse_number(cur_column()), ". ", .), .names = 'new_{col}')) %>% 
  unite(New_Col, starts_with('new'), na.rm = TRUE, sep = ' - ') %>% 
  mutate(New_Col = str_replace(New_Col, ' \\- \\d{1,2}\\. NA', '')) %>% 
  select(New_Col) %>% 
  as_tibble()
 New_Col           
  <chr>             
1 1. A - 2. B - 3. C
2 1. D - 2. E 
  • Related