-2

I want to unite the texts of columns in one string , I am trying like this but not working for me

df <- data.frame(A1 = c("class","type","class","type","class","class","class","class","class"),
                 B1 = c("b2","b3","b3","b1","b3","b3","b3","b2","b1"),
                 C1 = c(22,56,43,56,1,5,7,8,NA),
                 C1T=c(NA,  "Part of other business",   NA, NA, NA, NA, "temprorary", NA, NA))

the output should be like enter image description here

str_rst
  • 173
  • 4

3 Answers3

1

I am not sure if you want to do this for all the columns or only C, for all the columns you could do

> sapply(df,function(x){paste0(na.omit(x),collapse=",")})

                                                   A1 
"class,type,class,type,class,class,class,class,class" 
                                                   B1 
                         "b2,b3,b3,b1,b3,b3,b3,b2,b1" 
                                                  C1T 
                  "Part of other business,temprorary" 
user2974951
  • 9,535
  • 1
  • 17
  • 24
  • I am trying like this but not getting expecting output: var1 <- "C1T" var1 <- rlang::parse_expr(var1) group_byy <- "B1" group_byy <- rlang::parse_expr(group_byy) Texts <- df %>% select(!!group_byy, !!var1) %>% group_by(!!group_byy) %>% summarise(Comments=toString(!!var1),collapse = " ") %>% select(Comments) %>% unlist() %>% gsub("NA","", .) %>% stringi::stri_trim_both() – str_rst Jul 26 '21 at 06:09
  • To make it like the data frame you showed, just add data.frame() argument like so: data.frame(text=sapply(df,function(x){paste0(na.omit(x),collapse=",")})) – torpzorrr Jul 26 '21 at 06:29
1

You could try this code: It removes all NA rows. then after grouping use summarise with toString()

library(dplyr)
library(tidyr)
df %>%  
    drop_na() %>%  
    group_by(B1 )%>%
    summarise(Texts = toString(C1T)) %>% 
    select(-B1)
# A tibble: 1 x 1
  Texts                             
  <chr>                             
1 Part of other business, temprorary
TarJae
  • 72,363
  • 6
  • 19
  • 66
0

If you want to do this dynamically or in a function -

library(dplyr)

var1 <- "C1T"
group_byy <- "B1" 

df %>%
  group_by(.data[[group_byy]]) %>%
  summarise(Texts = toString(na.omit(.data[[var1]]))) %>%
  filter(Texts != '')

#  B1    Texts                             
#  <chr> <chr>                             
#1 b3    Part of other business, temprorary
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I have tried this but giving extra comma before string Texts<- df %>% group_by(!!group_byy )%>% summarise(Texts = toString(coalesce(!!var1 ),collapse = " "))%>% select(-!!group_byy ) %>% unlist() %>% gsub(c("NA",","),"", .) – str_rst Jul 26 '21 at 09:18