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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.