[R] create new

Jim Lemon drjimlemon at gmail.com
Sat Mar 25 11:34:25 CET 2017


Hi Val,
How about this:

cinmat<-
 matrix(c(mydat$x1>0,mydat$x1==0&mydat$x2==0,mydat$x1==0&mydat$x2>0),
 ncol=3)

mydat$x4<-rowSums(mydat[,c("x1","x3","x2")]*cinmat)

Jim


On Sat, Mar 25, 2017 at 2:56 PM, Val <valkremk at gmail.com> wrote:
> Hi all,
>
>
> I have several variables in a group and one group  contains three
> variables. Sample of data ( Year, x1, x3 and x2)
>
> mydat <- read.table(header=TRUE, text=' Year  x1  x3  x2
> Year1  10  12    0
> Year2   0  15    0
> Year3   0   0    20
> Year4  25   0   12
> Year5  15  25   12
> Year6   0  16   14
> Year7   0  10    0')
>
> I want create another variable( x4) based on the following condition.
>
> if x1  > 0  then x4 = x1; regardless of  x2 and x3 values.
> if x1  = 0  and x2  > 0 then x4 = x2;
> if x1  = 0 and  x2  = 0 then x4 = x3
>
> The desired output looks like as follows
> Year    x1  x3  x2   x4
> Year1  10  12    0  10
> Year2    0  15    0  15
> Year3    0    0   20  20
> Year4  25    0   12  25
> Year5  15  25   12  15
> Year6    0  16   14  14
> Year7    0  10     0  10
>
> Thank you in advance
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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