表中的重组数据

时间:2018-06-13 08:09:30

标签: r statistics data.table

我想将此data.table(行转换为列)转换为:

我的问题:

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

我需要:

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

我测试了所有这些选项:

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

但所有这些选项都不适合这个问题。

干杯

2 个答案:

答案 0 :(得分:0)

由于您已经在使用data.table,请使用data.table的 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")

结果:

   TIME   1   2
1: 1991 3.5 3.4
2: 1992 4.2 8.5

答案 1 :(得分:0)

使用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
相关问题