【问题标题】:How to create `id` for `pivot_longer()`如何为 `pivot_longer()` 创建 `id`
【发布时间】:2020-11-10 01:50:31
【问题描述】:

我在尝试从下面的dat 制作长格式数据方面已经完成了一半。

两个小问题:在我下面的pivot_longer() 代码中,

(1)如何为times 的数量添加id 变量,如我的预期输出所示?

(2)如何将列time1, . . .,time8 转为0, . . ., 7?

dat <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/wi.csv')

# Top 3 rows of current data:

      time1    time2     time3     time4     time5     time6    time7    time8       ses
1  1.203999 2.278898  3.716495  3.550721  3.375575  4.029231 5.292819 4.117426 -0.428465
2  0.291965 1.882300  0.958540  0.793806  0.021239  1.709134 3.127197 1.713560 -0.831093
3 -0.634382 0.847460 -0.801319 -0.126182 -0.496423 -1.009533 1.067997 0.131556  0.936131

# Top 3 rows of EXPECTED output:

  id       ses   Reading  time 
1  1 -0.428465  1.203999     0      
2  1 -0.428465  2.278898     1     
3  1 -0.428465  3.716495     2     
 
# What I tried:-----------------------------------------------------------------
pivot_longer(dat, time1:time8, names_to = "time", values_to = "Reading")

        ses  time  Reading
1 -0.428465 time1 1.203999
2 -0.428465 time2 2.278898
3 -0.428465 time3 3.716495

【问题讨论】:

    标签: r dataframe dplyr tidyverse


    【解决方案1】:

    您可以在获取长格式数据之前创建一个id 变量,并为每个id 创建一个time 列,即当前行号-1。

    library(dplyr)
    library(tidyr)
    
    dat %>%
      mutate(id = row_number()) %>%
      pivot_longer(cols = time1:time8, names_to = "time", values_to = "Reading") %>%
      group_by(id) %>%
      mutate(time = row_number() - 1)
    
    #     ses    id  time Reading
    #    <dbl> <int> <dbl>   <dbl>
    # 1 -0.428     1     0   1.20 
    # 2 -0.428     1     1   2.28 
    # 3 -0.428     1     2   3.72 
    # 4 -0.428     1     3   3.55 
    # 5 -0.428     1     4   3.38 
    # 6 -0.428     1     5   4.03 
    # 7 -0.428     1     6   5.29 
    # 8 -0.428     1     7   4.12 
    # 9 -0.831     2     0   0.292
    #10 -0.831     2     1   1.88 
    # … with 1,590 more rows
    

    【讨论】:

    • 它创建一个从 1 到 100 的行号,即数据中的行数。
    • pivot_longer 就是这样工作的。对于cols 中未包含的列,将展开/重复。
    • 哦,我明白了,我们有宽格式的1:200 id,每个都重复了被拉长的列数,对吧?
    【解决方案2】:

    在基础 R 中你可以这样做:

    cbind(dat[9],stack(dat,-9))
    

    甚至

     reshape(dat,1:8, dir="long",sep="")
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2020-02-01
      • 2021-10-31
      • 2022-11-28
      • 1970-01-01
      • 2021-12-23
      • 2013-02-28
      • 2018-01-22
      • 2020-11-23
      相关资源
      最近更新 更多