Search code examples
rdplyr

How to add rows in R already grouped?


I have this dataset

 dat=structure(list(A = c("n", 
                                                                     
  "n", "F", "F"), Par = c(1, 
                                                                                                                
   1, 8, 3), var = c(1, 10, 1,5), dat = c("T", 
                                                                                                                                                       
   "T", "T", "T")), row.names = c(NA, 4L                                                                                                                                                    
    ), class = "data.frame")

I want to add by the groups in A , i tried this did not work:

  dat%>%group_by(A)%>% mutate(ye = c( "40-25", "25-200")) 
    

Error:

 ! Assigned data `value` must be compatible with existing data.
  ✖ Existing data has 4 rows.
  ✖ Assigned data has 2 rows.
  ℹ Only vectors of size 1 are recycled.
  Run `rlang::last_error()` to see where the error occurred.

Desired output:

    A Par var dat     ye
  1 n   1   1   T  "40-25"
  2 n   1  10   T  "25-200"
  3 F   8   1   T  "40-25"
  4 F   3   5   T  "25-200" 

Solution

  • Probably you can try summarise_all + unnest

    library(dplyr)
    library(tidyr)
    
    dat %>%
      group_by(A) %>%
      summarise_all(list) %>%
      mutate(ye = list(c("40-25", "25-200"))) %>%
      unnest(cols = c(Par, var, dat, ye))
    

    which gives

      A       Par   var dat   ye    
      <chr> <dbl> <dbl> <chr> <chr>
    1 F         8     1 T     40-25
    2 F         3     5 T     25-200
    3 n         1     1 T     40-25
    4 n         1    10 T     25-200