具有选定值的数据框

Pivot data frame with selected value

我有这个数据框

df <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), Type = c("Date", "Text", "Value", "Text", "Date", "Value", "Value", "Text", "Date" ), Parameter = c("2020-2-3", "String", 9.99, "String", "2020-2-4", 0, 10, "String", "2020-2-5")), class = "data.frame", row.names = c(NA,                                                                                                                           -9L))

我想要这个

    ID  Type    Parameter      Date
    1   Text    String         2020-2-3
    1   Value   9.99           2020-2-3
    2   Text    String         2020-2-4 
    2   Value   0              2020-2-4 
    3   Value   10             2020-2-5
    3   Text    String         2020-2-5

我的想法是

pivot_wider(names_from = Type, values_from = Parameter)

但它旋转所有列

在新列中获取 Type = Date 值,并 fill 它们与每个 ID 的先前值。

library(dplyr)
library(tidyr)

df %>%
  mutate(Date = replace(Parameter, Type != 'Date', NA)) %>%
  group_by(ID) %>%
  fill(Date, .direction = 'updown') %>%
  ungroup %>%
  filter(Type != 'Date') 
 
#     ID Type  Parameter Date    
#  <int> <chr> <chr>     <chr>   
#1     1 Text  String    2020-2-3
#2     1 Value 9.99      2020-2-3
#3     2 Text  String    2020-2-4
#4     2 Value 0         2020-2-4
#5     3 Value 10        2020-2-5
#6     3 Text  String    2020-2-5