-3

This is for R

date <- seq(as.Date("2020/03/11"), as.Date("2020/03/16"), "day")

x_pos_a <- c(1, 5, 4, 9, 0)

x_pos_b <- c(2, 6, 9, 5, 4)

like so [...]

I have a timeseries dataframe with 69 time points. The rows in the dataframe are dates. Four variables (pos, anx, ang, sad) have been measured from three populations (A, B, C). Three samples were drawn from each population (x, y, z). Currently, each combination of the variable, population, and sample forms a column in the dataframe. For example, "x_pos_A", "x_pos_B", "x_pos_C", x_anx_A"..."z_sad_b", "z_sad_c".

I want to reshape it in the following shape

"Date" "variables" "population" "sample" "value"

I have spend the last 3 hours searching for answers on the forum but have been unsuccessful.

Any help much appreciated! Thanks

RTERG
  • 1
  • 2
  • Can you show a small reproducble example with `dput` – akrun Mar 02 '21 at 01:18
  • Thanks akrun...I have tried to edit my comment and insert a code. I am sorry if this is not what you asked for. I tried to paste dput output but got a message that it was too long. I am brand new to R and stackoverflow and am still getting a hang of things. – RTERG Mar 02 '21 at 01:58
  • Hi RTERG, welcome to StackOverflow. Please see stackoverflow.com/help/minimal-reproducible-example and https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for help on what users mean when they ask for a reproducible example. You should include the structure of an example of your dataset either using `dput()` or showing the code used to construct it like: `a = c(1,2,3) b = c(2,4,5) data = data.frame(a=a, b=b)` or something like that. – Reilstein Mar 02 '21 at 03:38

1 Answers1

-1

You can use pivot_longer from tidyr :

tidyr::pivot_longer(df, 
                    cols = -date,
                    names_to = c('sample', 'variable', 'population'), 
                    names_sep = '_')

#    date       sample variable population value
#   <date>     <chr>  <chr>    <chr>      <dbl>
# 1 2020-03-11 x      pos      a              1
# 2 2020-03-11 x      pos      b              2
# 3 2020-03-12 x      pos      a              5
# 4 2020-03-12 x      pos      b              6
# 5 2020-03-13 x      pos      a              4
# 6 2020-03-13 x      pos      b              9
# 7 2020-03-14 x      pos      a              9
# 8 2020-03-14 x      pos      b              5
# 9 2020-03-15 x      pos      a              0
#10 2020-03-15 x      pos      b              4 

data

date <- seq(as.Date("2020/03/11"), as.Date("2020/03/15"), "day")
x_pos_a <- c(1, 5, 4, 9, 0)
x_pos_b <- c(2, 6, 9, 5, 4)
df <- data.frame(date, x_pos_a, x_pos_b)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213