0

我有同样的问题。我有这种顺序的数据:;=column

D1 ;hurs

1  ;0.12

1  ;0.23

1  ;0.34

1  ;0.01

2  ;0.24

2  ;0.67

2  ;0.78

2  ;0.98

我喜欢这样:

D1; X; X; X; X    
1;0.12; 0.23; 0.34; 0.01; 
2;0.24; 0.67; 0.78; 0.98;

我想对 D1 进行排序并想重塑它?有人有想法吗?我需要为 D1 的 7603 值执行此操作。

4

5 回答 5

1

挖掘不可能被认领的骷髅,为什么不使用aggregate()

dat = read.table(header = TRUE, sep = ";", text = "D1 ;hurs
1  ;0.12
1  ;0.23
1  ;0.34
1  ;0.01
2  ;0.24
2  ;0.67
2  ;0.78
2  ;0.98")
aggregate(hurs ~ D1, dat, c)
#   D1 hurs.1 hurs.2 hurs.3 hurs.4
# 1  1   0.12   0.23   0.34   0.01
# 2  2   0.24   0.67   0.78   0.98

如果 D1 中每个 id 的长度不一样,也可以reshape()先创建“时间”变量后使用 base R:

dat2 <- dat[-8, ]
dat2$timeSeq <- ave(dat2$D1, dat2$D1, FUN = seq_along)
reshape(dat2, direction="wide", idvar="D1", timevar="timeSeq")
#   D1 hurs.1 hurs.2 hurs.3 hurs.4
# 1  1   0.12   0.23   0.34   0.01
# 5  2   0.24   0.67   0.78     NA
于 2012-10-19T06:10:47.777 回答
1

我会调查哈德利的reshape包裹。它做了各种很棒的事情。下面的代码将适用于您的玩具示例,但可能有更优雅的方式来执行此操作。简单地说,您的数据已经出现在?melt表单中,因此您可以简单地?cast使用它。

另外,请查看这些链接

http://www.statmethods.net/management/reshape.html

http://had.co.nz/reshape/

library(reshape)

help(package=reshape)
?melt

D1 <- c(1,1,1,1,2,2,2,2)
hurs <- c(.12, .23, .34, .01, .24, .67, .78, .98)
var <- rep(paste("X", 1:4, sep=""), 2)

foo <- data.frame(D1, var, hurs)
foo

cast(foo, D1~var)
于 2011-03-09T20:29:45.580 回答
0

reshape2 实际上比 reshape 更好。使用 reshape 比 reshape2 使用更多的内存和时间(至少对于我使用类似 900 万行的特定示例)。

于 2012-12-08T18:35:38.913 回答
0

您可以查看 Hadley Wickham 的 reshape 包及其 cast() 函数

http://had.co.nz/reshape/

于 2011-03-09T20:33:21.827 回答
0

我假设每个 D1 的小时数不相等(7603 值)

txt = 'D1 ;hurs
 1 ;0.12
 1 ;0.23
 1 ;0.34
 1 ;0.01
 2 ;0.24
 2 ;0.67
 2 ;0.78
 2 ;0.98'

dat <- read.table(textConnection(txt),header=T,sep=";")
dat$Lp <- 1:nrow(dat)
dat <- dat[order(dat$D1,dat$Lp),]
out <- split(dat$hurs,dat$D1)
out <- sapply(names(out),function(x) paste(paste(c(x,out[[x]]),collapse=";"),";",sep="",collapse=""))
于 2011-03-10T09:05:45.453 回答