Gather multiple date/value columns using tidyr

前端 未结 5 1006
慢半拍i
慢半拍i 2020-12-19 17:14

I have a data set containing (amongst others) multiple columns with dates and corresponding values (repeated measurements). Is there a way to turn this into a long data set

5条回答
  •  醉酒成梦
    2020-12-19 17:26

    I had the exact same question and data format for a dataset I was working on. Crowdsourced the answer at work. A couple of us came up with a single tidyr and dplyr pipeline solution. Using the same simulated df from original question.

    df %>%
        gather(key = date_position, value = date, starts_with("date")) %>%
        gather(key = value_position, value = value, starts_with("value")) %>%
        mutate(date_position = gsub('[^0-9]', "", date_position),
               value_position = gsub('[^0-9]', "", value_position)) %>%
        filter(date_position == value_position) %>%
        select(-ends_with("position")) %>%
        arrange(id)
    

提交回复
热议问题