Search code examples
rsummarize

Summarize and paste values in second line of same row


I am trying to summarise the rows and paste the values in the second line but in the same row. I tried with following code but not getting the result. Can anyone help me

df1 <- data.frame(a = c("xyz","xyz"), b = c("C1 : 2", "C2 : 3"), c = c(2,2))
df1 %>% group_by(a) %>% summarise(years = cat(paste(b), sep="\n"))
C1 : 2
C2 : 3

Expected output

    a     years 
  xyz    C1 : 2 
         C2 : 3 

Solution

  • Another potential solution is to remove the values in the a column that you don't want, e.g.

    library(tidyverse)
    df1 <- data.frame(a = c("xyz","xyz"), b = c("C1 : 2", "C2 : 3"), c = c(2,2))
    df2 <- df1 %>%
      group_by(a) %>%
      summarise(years = b)
    
    df2[2,1] <- ""
    as.data.frame(df2)
    #    a  years
    #1 xyz C1 : 2
    #2     C2 : 3