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 containing (the others and) only two columns - one for dates and one for values - using tidyr
?
The following code produces an example data frame:
df <- data.frame(
id = 1:10,
age = sample(100, 10),
date1 = as.Date('2015-09-22') - sample(100, 10),
value1 = sample(100, 10),
date2 = as.Date('2015-09-22') - sample(100, 10),
value2 = sample(100, 10),
date3 = as.Date('2015-09-22') - sample(100, 10),
value3 = sample(100, 10))
The input table could (chance of 1
in 1.8x10^138
) look like this:
id age date1 value1 date2 value2 date3 value3
1 1 32 2015-08-01 37 2015-07-15 38 2015-09-09 81
2 2 33 2015-07-22 16 2015-06-26 1 2015-09-12 58
...
10 10 64 2015-07-23 78 2015-08-25 70 2015-08-05 90
What I finally want is this:
id age date value
1 1 32 2015-08-01 37
2 1 32 2015-07-15 38
3 1 32 2015-09-09 81
4 2 33 2015-07-22 16
5 2 33 2015-06-26 1
...
30 10 64 2015-08-05 90
Any help doing this in tidyr
or reshape
would be greatly appreciated.
I stumbled across this trying to learn about using
gather
with a mix of dates and values.The existing answers lose information about which instance the date-value pair came from, ie, instance 1 for date1 & value1, etc. This may not be important, but here's a tidyverse option that keeps the instance.
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
anddplyr
pipeline solution. Using the same simulated df from original question.There should be some efficient way, but this is one way.
Working separately for date and value,
Now join,
The same strategy but using
tidyr
instead looks as follows:After controlling the resulting dimensions (careful with
NA
values - there is also ana.rm
argument to thegather
function) I joined the data.frames using base/dplyr functions:I am certain there is a much more elgant way to both parts, but it did the trick.
This does a
reshape
and then sorts the rows.The first two lines just set up the
v.names
andvarying
arguments toreshape
.v.names
defines the new column names andvarying
, is a list whose two components contain logical selection vectors of thedate
andvalue
columns respectively.The last line of code does the sorting and can be omitted if the row order does not matter.
No packages are used.
giving the following where the id and time columns relate the output rows back to the input: