user321627
user321627

Reputation: 2572

How to convert the values in one column into new columns, the values in another column into rows, indexing values in a third column?

Suppose I have the following data.table in R:

> data.table(Group = c(rep(1, 5), rep(2,5), rep(3,5)), Type = c("A","B","C","D","E"), Value = c(1:15))

    Group Type Value
 1:     1    A     1
 2:     1    B     2
 3:     1    C     3
 4:     1    D     4
 5:     1    E     5
 6:     2    A     6
 7:     2    B     7
 8:     2    C     8
 9:     2    D     9
10:     2    E    10
11:     3    A    11
12:     3    B    12
13:     3    C    13
14:     3    D    14
15:     3    E    15

I would like to create a new data table where I have:

> dat <- data.table(A = c(1,6,11), B = c(2,7,12), C = c(3,8,13), D = c(4,9,14), E = c(5,10,15))
> rownames(dat) <- c("1","2","3")
> dat
    A  B  C  D  E
1:  1  2  3  4  5
2:  6  7  8  9 10
3: 11 12 13 14 15

where the rownames are now the Group values, the Type the column names, with the entries being the corresponding values from Values. Is there a way to do this using a function in data.table?

Upvotes: 1

Views: 371

Answers (1)

SamR
SamR

Reputation: 20492

Using data.table rather than tidyr functions:

dt  <- data.table(Group = c(rep(1, 5), rep(2,5), rep(3,5)), Type = c("A","B","C","D","E"), Value = c(1:15)) 

data.table::dcast(dt, Group  ~ Type, value.var = "Value")
#    Group  A  B  C  D  E
# 1:     1  1  2  3  4  5
# 2:     2  6  7  8  9 10
# 3:     3 11 12 13 14 15

Edit: I have made the data.table:: explicit because there is also reshape2::dcast().

Upvotes: 3

Related Questions