我有一个包含1000个ID及其值的数据框。根据ID将两列转换为单行的更好方法是什么。我在reshape包中使用了cast函数,但似乎只将一列转换为行。以下是我的数据集示例。
DF <- data.frame(ID=c("x1","x1","x1","x1","x2","x2","x2","x2"),
name1=c("T1","T1","T2","T2","T1","T1","T2","T2"),
name2=c("C1","C2","C1","C2","C1","C2","C1","C2"),T1_val=c(1.1,1.1,2.3,2.3,1.8,1.8,7.9,7.9),C1_val=c(1.1,2.6,1.1,2.6,1.8,3.6,1.8,3.6) )
> DF
ID name1 name2 T1_val C1_val
x1 T1 C1 1.1 1.1
x1 T1 C2 1.1 2.6
x1 T2 C1 2.3 1.1
x1 T2 C2 2.3 2.6
x2 T1 C1 1.8 1.8
x2 T1 C2 1.8 3.6
x2 T2 C1 7.9 1.8
x2 T2 C2 7.9 3.6
期望的输出:
ID T1 T2 C1 C2
x1 1.1 2.3 1.1 2.6
x2 1.8 7.9 1.8 3.6
由于
答案 0 :(得分:3)
你可以使用dplyr和tidyr组合这么简单:
let c1:int = unbox b
let c2 = b :?> int
产生
library(dplyr)
library(tidyr)
DF %>%
spread(name1, T1_val) %>%
spread(name2, C1_val)
PS:如果你想深入了解这些包,请看一下这个cheatsheet。