I have this dataframe
DFtest <- data.frame(Zone=rep(c("R1","R2","R3"),each=2),
Type=rep(c("C1","C2"),3),
N1=sample(1:6),
N2=sample(seq(0,1,length.out=6)),
N3=sample(letters[1:6]))
DFtest
Zone Type N1 N2 N3
1 R1 C1 2 0.4 c
2 R1 C2 5 1.0 a
3 R2 C1 4 0.6 e
4 R2 C2 3 0.2 d
5 R3 C1 1 0.0 b
6 R3 C2 6 0.8 f
I want to convert the factor Type to columns and the columns N1 to N3 to a factor. The desired final result should look like this:
Zone Ns Type.C1 Type.C2
1 R1 N1 2 5
2 R1 N2 0.4 1.0
3 R1 N3 c a
4 R2 N1 4 3
5 R2 N2 0.6 0.2
6 R2 N3 e d
7 R3 N1 1 6
8 R3 N2 0.0 0.8
9 R3 N3 b f
I’ve been trying to accomplished that by combining plyr, reshape, dcast, melt and so on but I could find the right way. Thank you very much
Here’s the “reshape2” approach:
Here is a base R approach using
reshape()andaggregate(). The row order can be fixed later usingorder().