如何将列转换为R中的行? [英] How to transform Columns to rows in R?

查看:234
本文介绍了如何将列转换为R中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I kind of have the same problem. I have data in this kind of order: ;=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值执行此操作。

I would like to sort it with respect to D1 and like to reshape it? Does anyone have an idea? I need to do this for 7603 values of D1.

推荐答案

挖掘不可能获得的骨骼,为什么不使用 aggregate()

Digging up skeletons not likely to ever be claimed, why not use 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的长度不同,则在首先创建时间变量后,还可以使用基数R reshape()

If the lengths of each id in D1 are not the same, you can also use base R reshape() after first creating a "time" variable:

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

这篇关于如何将列转换为R中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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