Home > Net >  Concatenating rows by group?
Concatenating rows by group?

Time:06-14

Assuming I have a table like this:

Name|ID|Path
Test|1|/home
Test|1|/service
Test|2|/about
Test|3|/about
Test|3|/service
Test|3|/contact

What I'm trying with this:

df <- df |>
group_by(ID) |>
mutate(pages = paste(Path,sep = ", ")) |>
ungroup()

Is to get to this:

Name|ID|pages
Test|1|/home, /service
Test|2|/about
Test|3|/about, /service, /contact

What am I doing wrong?

CodePudding user response:

Is the following code your tested solution? Not clear what | stands for in your post

df<- data.frame(Test=c("Test","Test","Test","Test","Test","Test"),
                ID=c(1,1,2,3,3,3),
                Path=c("/home","/service","/about","/about","/service","/contact"))

library(dplyr)
df<-df %>%
  group_by(ID) %>%
  mutate(pages = paste(Path,sep = ", ")) %>%
  ungroup()

If this is the case you can try something like this

df %>%
  group_by(ID) %>%
  summarise(pages = toString(Path)) %>%
  ungroup()

CodePudding user response:

you can try

df %>% 
  group_by(Test, ID) %>% 
  summarise(Path = toString(Path))
# A tibble: 3 x 3
# Groups:   Test [1]
  Test     ID Path                      
  <chr> <dbl> <chr>                     
1 Test      1 /home, /service           
2 Test      2 /about                    
3 Test      3 /about, /service, /contact
  • Related