[R] Factors to Columns

Dennis Murphy djmuser at gmail.com
Fri May 20 12:08:30 CEST 2011


Hi:

I'm not sure I have the student part right, but here's one way to get
the structure you're looking for with the reshape2 package:
Example:

dat <- data.frame(student = rep(1:10, 3),
                  val = round(rnorm(30, m = 22.5, s = 3.0), 1),
                  parm = factor(rep(c('AGE', 'SCHOOL', 'SCORE'), each = 10)))
library(reshape2)
dcast(dat, student ~ parm, value_var = 'val')
   student  AGE SCHOOL SCORE
1        1 24.9   20.1  19.5
2        2 23.3   23.2  24.1
3        3 22.0   23.5  24.4
4        4 23.3   22.8  23.2
5        5 23.1   25.3  22.4
6        6 22.5   31.4  27.1
7        7 21.8   18.8  24.6
8        8 23.9   23.0  24.8
9        9 25.2   28.0  22.5
10      10 22.8   21.5  21.3

HTH,
Dennis

On Fri, May 20, 2011 at 2:49 AM, David martin <vilanew at gmail.com> wrote:
>> str(data)
> 'data.frame':   250 obs. of  3 variables:
>  $ student: chr  "A" "B" "C" "D" ...
>  $ data   : num  20.2 20.4 22.5 22.1 23.3 ...
>  $ param   : Factor w/ 4 levels "AGE","SCHOOL",..: 1 1 1 1 1 1 1 1 1 1
>
>
> Hi , i would like to split the dataframe so that each level of param is a
> column
> At the end it should look like
>
>
>        AGE     SCHOOL ...
> A       20.2    20.4
> B       22.5    22.1
> C       23.1    24
> D       22      22.8
> ..
>
>
> is i use that contingency table:
> table(data$student,data$param) i will have such a similar table of what i
> want, except that i don't need counts but real data.
>
> How can i split levels of the dataframe into columns ??
>
> thanks
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list