3

I have a dataframe like this:

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

I would like to split "second" column into 2 columns, by the value of the column (values of the third column that correspond to value of 1 in the second column would form column 1). So I would get:

    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

I looked into reshape package but I couldn't figure out how to do it. I was able to get table that looks like that using xtabs, but I need this in a data frame, not table.

user1754606
  • 1,259
  • 2
  • 13
  • 18

3 Answers3

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
user1317221_G
  • 15,087
  • 3
  • 52
  • 78
4

To formulate Metrics's comment in an answer:

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
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
0

Ok, sorry, I found the way to do it:

dcast(df, first ~ second, value.var="third")
user1754606
  • 1,259
  • 2
  • 13
  • 18