【问题标题】:Error when using reshape to restructure data from wide to long data with multiple column使用 reshape 将具有多列的宽数据重组为长数据时出错
【发布时间】:2021-07-15 19:26:31
【问题描述】:

我正在尝试使用 reshape 从宽格式到长格式重组我的数据,但我不断收到错误消息。下面我写了我已经尝试过的代码和我得到的错误消息。

当前数据结构

patientid  Adh_catv1    Adh_catv2    Adh_catv3    Adh_threeitemsv1   Adh_threeitemsv2  Adh_threeitemsv3
70FD       optimal      optimal      optimal      86                 90                100
70LJ       suboptimal   suboptimal   optimal      40                 50                70
70ML       optimal      suboptimal   suboptimal   89                 55                50        

想要的结构

patientid  Visits    Adherence    Adherence_threeitem
70FD       visit1   optimal        86
70FD       visit2   optimal        90
70FD       visit3   optimal        100
70LJ       visit1   suboptimal     40
70LJ       visit2   suboptimal     50
70LJ       visit3   optimal        70
70ML       visit1   optimal        89
70ML       visit2   suboptimal     55
70ML       visit3   suboptimal     50

这是我迄今为止尝试过的


    reshape(df, direction = 'long',
        varying = c ('adh_catv1:Adh_threeitemsv3'),
        timevar = 'Visits',
        times = c ("visit1","visit2","visit3"),
        v.names = c ('adherence','adherence_threeitem),
        idvar = 'patientid')

Error in reshape(df, direction = "long", varying = c("adh_catv1:Adh_threeitemsv3"),  : 
  length of 'varying' must be the product of length of 'v.names' and length of 'times'

请告知我在上面的代码中做错了什么,或者建议使用其他功能的替代更简单的选项。

【问题讨论】:

  • c( 之间有一个额外的空格
  • 只做varying =-1,因为唯一不变的列是第一列:

标签: r reshape melt longitudinal


【解决方案1】:

这里最基本的代码是:

reshape(df,-1, dir="long", sep="")

    patientid time   Adh_catv Adh_threeitemsv id
1.1      70FD    1    optimal              86  1
2.1      70LJ    1 suboptimal              40  2
3.1      70ML    1    optimal              89  3
1.2      70FD    2    optimal              90  1
2.2      70LJ    2 suboptimal              50  2
3.2      70ML    2 suboptimal              55  3
1.3      70FD    3    optimal             100  1
2.3      70LJ    3    optimal              70  2
3.3      70ML    3 suboptimal              50  3

您可以添加其他变量以获得您想要的:

【讨论】:

  • 先生。 Onyambu,请问我们如何使用pivot_longer 重现相同的输出?
  • @AnoushiravanR 基本的 pivot_longer 代码将是 df%>%pivot_longer(-patientid, names_to = c(".value", "Visits"), names_pattern="(.*)(\\d+)")
  • @AnoushiravanR 你仍然可以使用name_sep 而不是name_pattern。即只使用names_sep="(?<=\\D)(?=\\d)"
  • @AnoushiravanR 只是使用了lookbehind,即(?<=\D) 表示最后匹配的值不是数字。然后使用了前瞻(?=\d),这意味着下一个值是一个数字。如果您查看宽数据框的名称,则分隔符应位于字符和数字之间
  • @AnoushiravanR 完成了你的工作,感觉很好。你会知道从长远来看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 2023-02-07
相关资源
最近更新 更多