0

I want to combine rows of character column descrb condition on the value of namefn.

df1 <-
  structure(list(namefn = c(".checkMFClasses", "", "AIC", "ARMAacf", 
"ARMAtoMA", "Beta"), descrb = c("Functions to Check the Type of Variables passed", 
"to Model Frames", "Akaike's An Information Criterion", "Compute Theoretical ACF for an ARMA Process", 
"Convert ARMA Process to Infinite MA Process", "The Beta Distribution"
)), row.names = c(NA, 6L), class = "data.frame")

df1

           namefn                                          descrb
1 .checkMFClasses Functions to Check the Type of Variables passed
2                                                 to Model Frames
3             AIC               Akaike's An Information Criterion
4         ARMAacf     Compute Theoretical ACF for an ARMA Process
5        ARMAtoMA     Convert ARMA Process to Infinite MA Process
6            Beta                           The Beta Distribution

Required Output

           namefn                                                          descrb
1 .checkMFClasses Functions to Check the Type of Variables passed to Model Frames
2             AIC                               Akaike's An Information Criterion
3         ARMAacf                     Compute Theoretical ACF for an ARMA Process
4        ARMAtoMA                     Convert ARMA Process to Infinite MA Process
5            Beta                                           The Beta Distribution

I tried the following code

library(tidyverse)

df1 %>% 
  mutate(descrb = if_else(namefn == "", "Merge", descrb))
MYaseen208
  • 22,666
  • 37
  • 165
  • 309

1 Answers1

1

You can replace empty values with NA, fill them with latest non-NA value and for each namefn combine the descrb values.

library(dplyr)

df1 %>%
  mutate(namefn = na_if(namefn, "")) %>%
  tidyr::fill(namefn) %>%
  group_by(namefn) %>%
  summarise(descrb = paste0(descrb, collapse = " "))


# A tibble: 5 x 2
#  namefn          descrb                                                          
#  <chr>           <chr>                                                           
#1 .checkMFClasses Functions to Check the Type of Variables passed to Model Frames
#2 AIC             Akaike's An Information Criterion                               
#3 ARMAacf         Compute Theoretical ACF for an ARMA Process                     
#4 ARMAtoMA        Convert ARMA Process to Infinite MA Process                     
#5 Beta            The Beta Distribution                                  
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213