重塑多id重复变量读数,从长到宽 [英] reshape multi id repeated variable readings from long to wide

查看:84
本文介绍了重塑多id重复变量读数,从长到宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

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) 

这就是我想要的:

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) 

问题在于我的变量速度权重和时间是重复的。我可以使用带if语句的for循环来完成它,但是这很麻烦而且效率不高。这是我关于stackoverflow的第一篇文章...长期以来的首次用户问题...谢谢你们!

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!

推荐答案

使用<$来自data.table的c $ c> rowid (非常类似于@ Kelli-Jean的答案):

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

或在一行中 dcast(testdf,id + data.table :: rowid(measure)〜measure)

或不使用data.table,添加 testdf $ r<-ave(testdf $ id,testdf $ meas,FUN = seq_along )

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

或者如果您打算学习data.table软件包:

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)

这篇关于重塑多id重复变量读数,从长到宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆