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

r - Reshape data from long to wide, with time in new wide variable name

I have a data frame that I would like to merge from long to wide format, but I would like to have the time embedded into the variable name in the wide format. Here is an example data set with the long format:

id <- as.numeric(rep(1,16))
time <- rep(c(5,10,15,20), 4)
varname <- c(rep("var1",4), rep("var2", 4), rep("var3", 4), rep("var4", 4))
value <- rnorm(16)
tmpdata <- as.data.frame(cbind(id, time, varname, value))

> tmpdata
id time varname              value
1    5    var1  0.713888426169224
1   10    var1   1.71483653545922
1   15    var1  -1.51992072577836
1   20    var1  0.556992407683219
....
4   20    var4   1.03752019932467

I would like this in a wide format with the following output:

id var1.5 var1.10 var1.15 var1.20 ....
1  0.71   1.71    -1.51   0.55 

(and so on)

I've tried using reshape function in base R without success, and I was not sure how to accomplish this using the reshape package, as all of the examples put time as another variable in the wide format. Any ideas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is trivial with the reshape package:

library(reshape)
cast(tmpdata, ... ~ varname + time)

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

...