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
322 views
in Technique[技术] by (71.8m points)

r - reshape multi id repeated variable readings from long to wide

This is what I have:

id<-c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2)
measure<-c("speed","weight","time","speed","weight","time","speed","weight","time",
           "speed","weight","time","speed","weight","time","speed","weight","time")
value<-c(1.23,10.3,33,1.44,10.4,31,1.21,10.1,33,4.25,12.5,38,1.74,10.8,31,3.21,10.3,33)
testdf<-data.frame(id,measure,value) 

This is what I want:

id<-c(1,1,1,2,2,2)  
speed<-c(1.23,1.44,1.21,4.25,1.74,3.21)
weight<-c(10.3,10.4,10.1,12.5,10.8,10.3)
time<-c(33,31,33,37,31,33)
res<-data.frame(id,speed,weight,time) 

The issue lies in that my variables speed weight and time are repeated. I can get it done with a for loop with if statements but its a major headache and not very efficient. This is my first post on stackoverflow ... long time user first time question ... thanks yall!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Using rowid from data.table (very similar to @Kelli-Jean's answer):

library(reshape2)

testdf$r <- data.table::rowid(testdf$measure); 
dcast(testdf, id + r ~ measure)

  id r speed time weight
1  1 1  1.23   33   10.3
2  1 2  1.44   31   10.4
3  1 3  1.21   33   10.1
4  2 4  4.25   38   12.5
5  2 5  1.74   31   10.8
6  2 6  3.21   33   10.3

Or in one line dcast(testdf, id + data.table::rowid(measure) ~ measure).

Or without data.table, add like testdf$r <- ave(testdf$id, testdf$meas, FUN = seq_along).

Or if you're up for learning the data.table package:

library(data.table)
setDT(testdf)
testdf[, r := rowid(measure)]
dcast(testdf, id + r ~ measure)

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

...