0

Asked a similar previous question but cant seem to alter the code to get the desired outcome:

my data frame is df:

    date    tss
 2020-05-29  71
 2020-05-29  60
 2020-05-30  42
 2020-05-31  NA
 2020-06-01  95
 2020-06-01  82
 2020-06-02  69
 2020-06-03 103
 2020-06-04  49
 2020-06-05  74
 2020-06-05  49
 2020-06-06  NA
 2020-06-07  NA
 2020-06-08  NA
 2020-06-09  50
 2020-06-10 191
 2020-06-11 125
 2020-06-11 126
 2020-06-12 104
 2020-06-12  77

Would like to move the tss scores that occur more than once (twice in the same day) into a new column where there is only one row for each date(date is classified as a date).

for example:

 date        tss   tss2
 2020-05-29  71     60
 2020-05-30  42     0
 2020-05-31  NA
 2020-06-01  95     82

There will only ever be 2 tss entries for the same date. tried utilising group_by and pivot_wider but to no success.

thank you.

BigBird
  • 5
  • 3
  • `df %>% group_by(date) %>% mutate(colname = paste0('tss', row_number())) %>% tidyr::pivot_wider(names_from = colname, values_from = tss)` – Ronak Shah Jul 27 '20 at 00:07

1 Answers1

-1

Try this:

library(tidyverse)

#Data
df <- structure(list(date = c("2020-05-29", "2020-05-29", "2020-05-30", 
"2020-05-31", "2020-06-01", "2020-06-01", "2020-06-02", "2020-06-03", 
"2020-06-04", "2020-06-05", "2020-06-05", "2020-06-06", "2020-06-07", 
"2020-06-08", "2020-06-09", "2020-06-10", "2020-06-11", "2020-06-11", 
"2020-06-12", "2020-06-12"), tss = c(71L, 60L, 42L, NA, 95L, 
82L, 69L, 103L, 49L, 74L, 49L, NA, NA, NA, 50L, 191L, 125L, 126L, 
104L, 77L)), class = "data.frame", row.names = c(NA, -20L))

#Code
df %>% group_by(date) %>% mutate(i=row_number(date)) %>%
  pivot_wider(names_from = i,values_from = tss)

# A tibble: 15 x 3
# Groups:   date [15]
   date         `1`   `2`
   <chr>      <int> <int>
 1 2020-05-29    71    60
 2 2020-05-30    42    NA
 3 2020-05-31    NA    NA
 4 2020-06-01    95    82
 5 2020-06-02    69    NA
 6 2020-06-03   103    NA
 7 2020-06-04    49    NA
 8 2020-06-05    74    49
 9 2020-06-06    NA    NA
10 2020-06-07    NA    NA
11 2020-06-08    NA    NA
12 2020-06-09    50    NA
13 2020-06-10   191    NA
14 2020-06-11   125   126
15 2020-06-12   104    77
Duck
  • 39,058
  • 13
  • 42
  • 84