如何在R中多次成功使用reshape()函数? [英] How do I use the reshape() function more than once successfully in R?
问题描述
这是我的数据框:
ID Group x1 x2 x3 y1 y2 y3 z1 z2 z3
144 1 566 613 597 563 549 562 599 82 469
167 2 697 638 756 682 695 693 718 82 439.5
247 4 643 698 730 669 656 669 698 82 514.5
317 4 633 646 641 520 543 586 559 82 405.5
344 3 651 678 708 589 608 615 667 82 514
352 2 578 702 671 536 594 579 591 82 467.5
382 1 678 690 693 555 565 534 521 82 457.5
447 3 668 672 718 663 689 751 784 82 506.5
464 2 760 704 763 514 554 520 564 82 486
628 1 762 789 783 618 610 645 625 82 536
我有几种重复的宽幅测量方法,我想将其重塑为长幅测量.我不确定如何一次重塑所有三个(x,y,z)重复变量,因此我选择了一个接一个地尝试.这样我就可以成功地重塑变量x:
I have several repeated measures in wide format which I would like to reshape into long format. I wasn't sure how to reshape all the three (x,y,z) respeated variables at once, so I opted for trying one after the other. So I could successfully reshape variable x:
reshaped.df <- reshape(df,
idvar="ID",
varying= c("x.1", "x.2", "x.3"),
timevar="Timex",
v.names= "X",
times=c("Part1", "Part2", "Part3"),
direction="long")
然后,当我尝试在新的重塑数据帧上使用相同的重塑方法来融合下一个变量时,它将不再起作用. 因此,我尝试运行此代码:
When I then try to use the same reshape method on the new reshaped dataframe to melt the next variable, it doesn't work anymore. So I try to run this:
reshaped.df <- reshape(reshaped.df,
idvar="ID",
varying= list( c("y.1", "y.2", "y.3")),
timevar="Timey",
v.names= "Y",
times=c("P1", "P2", "P3"),
direction="long")
我收到以下错误和警告消息:
And I get the following error and warning message:
Error in `row.names<-.data.frame`(`*tmp*`, value = paste(d[, idvar], times[1L], :
duplicate 'row.names' are not allowed
In addition: Warning message:
non-unique values when setting 'row.names': ‘144.Part1’, ‘167.Part1’, ‘247.Part1’, ‘317.Part1’, ‘344.Part1’, ‘352.Part1’, ‘382.Part1’, ... <truncated>
还有另一种方法可以有效地做到这一点吗?
Is there another way to do this efficiently?
推荐答案
我会使用reshape
做这样的事情:
I would do something like this using reshape
:
vars <- names(df)[grepl("(x|y|z)",names(df))]
res <- reshape(df, varying=vars, v.names = c("x","y","z"), direction = "long")
head(res)
# ID Group time x y z id
#1.1 144 1 1 566 613 597 1
#2.1 167 2 1 697 638 756 2
#3.1 247 4 1 643 698 730 3
#4.1 317 4 1 633 646 641 4
#5.1 344 3 1 651 678 708 5
#6.1 352 2 1 578 702 671 6
这篇关于如何在R中多次成功使用reshape()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!