Home > database >  how to bind rows into one row but still keep original rows
how to bind rows into one row but still keep original rows

Time:08-26

I have a df that looks like the on the left. I would like to put all rows inputs into one row,and still keep old rows. How should I do this?

enter image description here

df<-structure(list(c1 = c("Student Enrollment", "750"), c2 = c("Faculty Number", 
"21"), c3 = c("Graduated", "65")), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

CodePudding user response:

output = rbind(df, lapply(df, paste, collapse = "\n"))
output
#                        c1                 c2            c3
# 1      Student Enrollment     Faculty Number     Graduated
# 2                     750                 21            65
# 3 Student Enrollment\n750 Faculty Number\n21 Graduated\n65

In the console, line breaks print as \n. If you View() it they will print as spaces. There are probably some nice table formatting packages that actually display linebreaks within a cell.

You could, of course, replace "\n" in my code with " " to use a space instead of a linebreak.

CodePudding user response:

A base solution similar to @GregorThomas':

rbind(df, do.call(paste, c(asplit(df, 1), sep = "\n")))

# A tibble: 3 × 3
  c1                        c2                   c3             
  <chr>                     <chr>                <chr>          
1 "Student Enrollment"      "Faculty Number"     "Graduated"    
2 "750"                     "21"                 "65"           
3 "Student Enrollment\n750" "Faculty Number\n21" "Graduated\n65"

If you write the data out to an excel file (e.g. openxlsx::write.xlsx), \n will be presented as linebreaks.

CodePudding user response:

A possible solution is below. In case we need to have the concatenated number in a different line, we can use collapse = "\n" instead:

library(tidyverse)

bind_rows(df, map_dfr(df, ~ str_c(.x, collapse = " ")))

#> # A tibble: 3 × 3
#>   c1                     c2                c3          
#>   <chr>                  <chr>             <chr>       
#> 1 Student Enrollment     Faculty Number    Graduated   
#> 2 750                    21                65          
#> 3 Student Enrollment 750 Faculty Number 21 Graduated 65

CodePudding user response:

We could use summarise with across

library(stringr)
library(dplyr)
df %>% 
   summarise(across(everything(), ~ c(.x, str_c(.x, collapse = " "))))

-output

# A tibble: 3 × 3
  c1                     c2                c3          
  <chr>                  <chr>             <chr>       
1 Student Enrollment     Faculty Number    Graduated   
2 750                    21                65          
3 Student Enrollment 750 Faculty Number 21 Graduated 65
  •  Tags:  
  • r
  • Related