[R] creating dummy variables based on conditions

Rui Barradas ruipbarradas at sapo.pt
Sun Jul 14 16:01:38 CEST 2013


Hello,

Your data seems to be of class 'matrix'. The following code needs it to 
be a data.frame.

dat <- as.data.frame(your input matrix)

res <- do.call(rbind, lapply(split(dat, list(dat$id, dat$year)), 
function(x){
	x$ans <- if(any(x$var == 1)) 1 else 0
	x}))
rownames(res) <- NULL
res


Hope this helps,

Rui Barradas

Em 14-07-2013 12:30, Anup Nandialath escreveu:
> Hello everyone,
>
> I have a dataset which includes the first three variables from the demo
> data below (year, id and var). I need to create the new variable ans as
> follows
>
> If var=1, then for each year (where var=1), i need to create a new dummy
> ans which takes the value of 1 for all corresponding id's where an instance
> of one was recorded. Sample data with the output is shown below.
>
>      year    id var ans
> [1,] 2010  1   1   1
> [2,] 2010  2   0   0
> [3,] 2010  1   0   1
> [4,] 2010  1   0   1
> [5,] 2011  2   1   1
> [6,] 2011  2   0   1
> [7,] 2011  1   0   0
> [8,] 2011  1   0   0
>
> Any help on how to achieve this is much appreciated.
>
> Thanks
> Anup
>
> 	[[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.
>



More information about the R-help mailing list