简体   繁体   中英

Is there a function in R to aggregate rows with same values in some columns but different in others?

My db example:

      n_historia fecha      hemo_detalle                                                                  
  <chr>      <date>     <chr>                                                                         
1 1155148    2020-11-01 Serratia marcescens
2 1155148    2020-11-06 Klebsiella
3 1155148    2020-11-06 NEGATIVO

Expected output:

  n_historia fecha.x      hemo_detalle.x       fecha.y     hemo_detalle.y  fecha.z     hemo_detalle.z                                                              
  <chr>      <date>       <chr>                <date>      <chr>           <date>      <chr>                                                              
1 1155148    2020-11-01   Serratia marcescens  2020-11-06  Klebsiella      2020-11-06  NEGATIVO

Thanks for any help you can offer.

Reproducible sample data

structure(list(n_historia = c(1155148, 1155148, 1155148), fecha = c("2020-11-01", 
"2020-11-06", "2020-11-06"), hemo_detalle = c("Serratia marcescens", 
"Klebsiella", "NEGATIVO")), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

You can use:

library(dplyr)
library(tidyr)

df %>%
  group_by(n_historia) %>%
  mutate(row = row_number()) %>%
  pivot_wider(names_from = row, values_from = c(fecha, hemo_detalle)) %>%
  ungroup

#  n_historia fecha_1    fecha_2    fecha_3    hemo_detalle_1     hemo_detalle_2 hemo_detalle_3
#       <int> <chr>      <chr>      <chr>      <chr>              <chr>          <chr>         
#1    1155148 2020-11-01 2020-11-06 2020-11-06 Serratiamarcescens Klebsiella     NEGATIVO      

We could use rowid

library(dplyr)
library(tidyr)
library(data.table)
df %>%
    mutate(row = rowid(n_historia)) %>%   
    pivot_wider(names_from = row, values_from = c(fecha, hemo_detalle)) %>%
    ungroup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM