Combining rows with the same value into one column

Hi @beginnersluke,

It is strongly recommended to keep your data as "long" for most tasks. It makes it much easier to plot, clean, etc.

However, since I don't know how you plan to use the data, here is a solution anyway:

library(tidyverse)
library(lubridate)

data <- 
tribble(
  ~Name, ~Date, ~Systolic, ~Diastolic,
  'John',   '1/1/10',   132,    92,
  'Amy',    '1/2/10',   120,    80,
  'John',   '2/2/10',   135,    92,
  'Amy',    '2/2/10',   82, 118,
  'Nick',   '2/14/10',  108,    72,
  'Amy',    '3/1/10',   122,    80,
  'John',   '3/3/10',   128,    88
)

data %>% 
  mutate(Date = mdy(Date)) %>% 
  arrange(Name, Date) %>% 
  group_by(Name) %>% 
  mutate(Visit = 1:n()) %>% 
  ungroup() %>% 
  pivot_wider(
    names_from = Visit, 
    values_from = c(Date, Systolic, Diastolic),
    names_sep = ''
  )
#> # A tibble: 3 x 10
#>   Name  Date1      Date2      Date3      Systolic1 Systolic2 Systolic3
#>   <chr> <date>     <date>     <date>         <dbl>     <dbl>     <dbl>
#> 1 Amy   2010-01-02 2010-02-02 2010-03-01       120        82       122
#> 2 John  2010-01-01 2010-02-02 2010-03-03       132       135       128
#> 3 Nick  2010-02-14 NA         NA               108        NA        NA
#> # … with 3 more variables: Diastolic1 <dbl>, Diastolic2 <dbl>, Diastolic3 <dbl>

Created on 2020-02-12 by the reprex package (v0.3.0)

3 Likes