[R] mapple

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Wed Oct 2 05:24:43 CEST 2019


Hi Phillip,
The following seems to do what you want:

phdf<-read.table(text="v1 v2 v3 v4 v5 code
 0  0  0  0  0    1
 1  4  0  0  0    1
 1  1  0  0  0    1
 1  0  1  0  0    1
 2  0  1  0  0    1
 0  1  0  0  0    1
 0  1  2  0  0    1
 0  1  2  3  0    1
 0  2  3  4  4    1
 0  0  0  2  3    1",
 header=TRUE,
 stringsAsFactors=FALSE)
rules<-list("x[1]==0&&x[2]==0&&x[3]==0&&x[4]==0&&x[5]==0",
 "x[1]==1&&x[2]==1","x[1]==0&&x[2]==1&&x[3]==2")
outcomes<-c(1,5,10)
apply_rule<-function(x,rule) return(eval(parse(text=rule)))
for(ri in 1:length(rules))
 phdf[apply(phdf,1,apply_rule,rules[[ri]]),"code"] <- outcomes[ri]

and can be expanded to the number of rules that you want. BUT, you
have not specified a non-match value, so your initial values for
"code" will persist.

Jim

On Wed, Oct 2, 2019 at 12:32 PM Phillip Heinrich <herd_dog using cox.net> wrote:
>
> With the snippet of data below I’m trying to do an if/then type of thing:
>     row 1 – if all five variables equal 0 then code equals 1;
>     row 3 – if v1 = 1 and v2 = 1 then code = 5;
>     row 7 – if v1 = 0 and v2 = 1 and v3 = 2 then code = 10
>
> There are 24 codes in the complete database.
>
>
>    v1 v2 v3 v4 v5 code
> 1   0  0  0  0  0    1
> 2   1  4  0  0  0    1
> 3   1  1  0  0  0    1
> 4   1  0  1  0  0    1
> 5   2  0  1  0  0    1
> 6   0  1  0  0  0    1
> 7   0  1  2  0  0    1
> 8   0  1  2  3  0    1
> 9   0  2  3  4  4    1
> 10  0  0  0  2  3    1  I understand that the mapply function can do things like this but I have been reading documentation and poking around with Google but am getting nowhere.  Any advise whould be greatly appreciated.
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using 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