r: split column into multiple columns by value
r, reshape
Solution
set.seed(1)
df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5),
third = rnorm(10))
library(reshape2)
dcast(df, first ~ second)
#Using third as value column: use value.var to override.
# first 1 2
#1 A -0.6264538 -0.8204684
#2 B 0.1836433 0.4874291
#3 C -0.8356286 0.7383247
#4 D 1.5952808 0.5757814
#5 E 0.3295078 -0.3053884
Problem
I have a dataframe like this: ``` df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), third = rnorm(10)) ``` . ``` > df first second third 1 A 1 -0.47175662 2 B 1 0.92905470 3 C 1 -0.79385274 4 D 1 0.68175904 5 E 1 -0.91112323 6 A 2 0.24941514 7 B 2 -0.74557229 8 C 2 0.92419408 9 D 2 0.34787484 10 E 2 -0.04578459 ``` I would like to split "second" column into 2 columns, by the value of the column (values of the third column that correspond to value of 1 in the second column would form column 1). So I would get: ``` first 1 2 1 A -0.47175662 0.24941514 2 B 0.9290547 -0.74557229 3 C -0.79385274 0.92419408 4 D 0.68175904 0.34787484 5 E -0.91112323 -0.04578459 ``` I looked into reshape package but I couldn't figure out how to do it. I was able to get table that looks like that using xtabs, but I need this in a data frame, not table.