1

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?

user321627
  • 2,350
  • 4
  • 20
  • 43
  • `data.table::data.table(Group = c(rep(1, 5), rep(2,5), rep(3,5)), Type = c("A","B","C","D","E"), Value = c(1:15)) %>% tidyr::pivot_wider(names_from = Type, values_from = Value) %>% dplyr::select(-Group)` – highlandsmain Jul 18 '22 at 13:57
  • Does this answer your question? [How to reshape data from long to wide format](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) (See the answer by SymbolixAU) – harre Jul 18 '22 at 14:02

1 Answers1

3

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().

SamR
  • 8,826
  • 3
  • 11
  • 33