Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

r - How to use "cast" in reshape without aggregation

In many uses of cast I've seen, an aggregation function such as mean is used.

How about if you simply want to reshape without information loss. For example, if I want to take this long format:

ID     condition    Value
John   a            2
John   a            3
John   b            4
John   b            5
John   a            6
John   a            2
John   b            1
John   b            4

To this wide-format without any aggregation:

ID    a  b
John  2  4
John  3  5
Alex  6  1
Alex  2  4

I suppose that this is assuming that observations are paired and you were missing value would mess this up but any insight is appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In such cases you can add a sequence number:

library(reshape2)

DF$seq <- with(DF, ave(Value, ID, condition, FUN = seq_along))
dcast(ID + seq ~ condition, data = DF, value.var = "Value")

The last line gives:

    ID seq a b
1 John   1 2 4
2 John   2 3 5
3 John   3 6 1
4 John   4 2 4

(Note that we used the sample input from the question but the sample output in the question does not correspond to the sample input.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...