[R] question about creating data frame

jim holtman jholtman at gmail.com
Tue May 15 21:42:31 CEST 2012


try this:


> x <- read.table(text = '"Not A" "A"
+ "Mathematics" 80 15
+ "Physics" 32 24
+ "Biology" 18 29', skip = 1, as.is = TRUE)
>
> # create the result
> result <- do.call(rbind, lapply(1:nrow(x), function(.row){
+     data.frame(course = x$V1[.row]
+         , A = c(rep(1, x$V2[.row]), rep(0, x$V3[.row]))
+         )
+ }))
>
> result
         course A
1   Mathematics 1
2   Mathematics 1
3   Mathematics 1
4   Mathematics 1
5   Mathematics 1
6   Mathematics 1
7   Mathematics 1
8   Mathematics 1
9   Mathematics 1
10  Mathematics 1
11  Mathematics 1
12  Mathematics 1
13  Mathematics 1
........
190     Biology 0
191     Biology 0
192     Biology 0
193     Biology 0
194     Biology 0
195     Biology 0
196     Biology 0
197     Biology 0
198     Biology 0



On Tue, May 15, 2012 at 2:47 PM, T Bal <studenttbal at gmail.com> wrote:
> Hello,
>
> My data is "study.txt":
>
> "Not A" "A"
> "Mathematics" 80 15
> "Physics" 32 24
> "Biology" 18 29
>
>
> I want to transform this data into with column names 'course' and 'A':
>
>                   course                       A
>             1   Mathematics              1
>             2   Mathematics              1
>             ..  ......                             ..
>            80  Mathematics              1
>            81  Mathematics              0
>            ...       ............                 ...
>            95  Mathematics              0
>            96  Physics                      1
>             ... ............                     ...
>           127 Physics                      1
>           128 Physics                      0
>           ...    ............                     ...
>           151  Physics                     0
>
>        etc.
>
>  How should I do it? So this data frame will consist from 198 rows.
>
> Thank you very much.
>
> kind regards,
> T. Bal
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list