0

I want to transform this data.table (rows to column):

My problem:

id  | TIME | VAR
----|------|-----
1   | 1991 | 3.5
1   | 1992 | 4.2
2   | 1991 | 3.4
2   | 1992 | 8.5

I need:

TIME |  1  |  2  |
-----|-----|-----|
1991 | 3.5 | 3.4 |
1992 | 4.2 | 8.5 |

I tested all of this options:

https://www.r-statistics.com/tag/transpose/ https://es.stackoverflow.com/questions/135093/c%C3%B3mo-transformar-filas-por-columnas-agrupando-una-variable

but all of these options are not suit for this problem.

Cheers

2 Answers2

0

Since you are already using a data.table, use data.table's dcast()

dt <- data.table(id = c(1,1,2,2),
                 TIME = c(1991,1992,1991,1992),
                 VAR = c(3.5,4.2,3.4,8.5))

dcast(dt, TIME ~ id, value.var = "VAR")

result:

   TIME   1   2
1: 1991 3.5 3.4
2: 1992 4.2 8.5
Wimpel
  • 26,031
  • 1
  • 20
  • 37
0

With tidyverse:

library(tidyverse)
df <- data.frame(id = c(1,1,2,2),
                 TIME = c(1991,1992,1991,1992),
                 VAR = c(3.5,4.2,3.4,8.5))


df%>%
 tidyr::spread(id,VAR)
 TIME   1   2
1 1991 3.5 3.4
2 1992 4.2 8.5
jyjek
  • 2,627
  • 11
  • 23