r:按值将列拆分为多个列

时间:2013-11-19 21:18:36

标签: r reshape

我有一个这样的数据框:

df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), 
                 third = rnorm(10))

> df
   first second       third
1      A      1 -0.47175662
2      B      1  0.92905470
3      C      1 -0.79385274
4      D      1  0.68175904
5      E      1 -0.91112323
6      A      2  0.24941514
7      B      2 -0.74557229
8      C      2  0.92419408
9      D      2  0.34787484
10     E      2 -0.04578459

我想通过列的值将“第二”列拆分为2列(第二列中与第1列中的值1对应的值将形成第1列)。所以我会得到:

    first    1        2
1   A   -0.47175662 0.24941514
2   B   0.9290547   -0.74557229
3   C   -0.79385274 0.92419408
4   D   0.68175904  0.34787484
5   E   -0.91112323 -0.04578459

我查看了重塑包,但我无法弄清楚如何做到这一点。我能够使用xtabs获得看起来像这样的表,但我需要在数据框中,而不是表。

3 个答案:

答案 0 :(得分:4)

set.seed(1)
df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), 
                  third = rnorm(10))
library(reshape2)
dcast(df, first ~ second)

#Using third as value column: use value.var to override.
#  first          1          2
#1     A -0.6264538 -0.8204684
#2     B  0.1836433  0.4874291
#3     C -0.8356286  0.7383247
#4     D  1.5952808  0.5757814
#5     E  0.3295078 -0.3053884

答案 1 :(得分:4)

在答案中制定度量标准的评论:

reshape(df, direction = "wide", idvar="first", timevar="second")
#   first     third.1     third.2
# 1     A  0.71266631  0.06016044
# 2     B -0.07356440 -0.58889449
# 3     C -0.03763417  0.53149619
# 4     D -0.68166048 -1.51839408
# 5     E -0.32427027  0.30655786

答案 2 :(得分:0)

好的,对不起,我找到了办法:

dcast(df, first ~ second, value.var="third")