简体   繁体   English

R:将复杂的时间序列 dataframe 转换为长

[英]R: Covernt a complex time series dataframe to long

This is for R这是针对 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.我有一个时间序列 dataframe 有 69 个时间点。 The rows in the dataframe are dates. dataframe 中的行是日期。 Four variables (pos, anx, ang, sad) have been measured from three populations (A, B, C).从三个群体(A、B、C)测量了四个变量(pos、anx、ang、sad)。 Three samples were drawn from each population (x, y, z).从每个群体(x、y、z)中抽取三个样本。 Currently, each combination of the variable, population, and sample forms a column in the dataframe.目前,变量、总体和样本 forms 的每个组合在 dataframe 中的一列。 For example, "x_pos_A", "x_pos_B", "x_pos_C", x_anx_A"..."z_sad_b", "z_sad_c".例如,“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.我花了最后 3 个小时在论坛上寻找答案,但没有成功。

Any help much appreciated!非常感谢任何帮助! Thanks谢谢

You can use pivot_longer from tidyr :您可以使用pivot_longertidyr

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM