[R] Computing calculation among two vectors
arun
smartpink111 at yahoo.com
Wed Sep 25 18:55:29 CEST 2013
I guess you meant something like:
res2<- sapply(y,function(i) outer(x,x,i))
row.names(res2)<- row.names(res)
identical(res2,res)
#[1] TRUE
#or is there any shorter way?
A.K.
________________________________
From: Bert Gunter <gunter.berton at gene.com>
To: arun <smartpink111 at yahoo.com>
Cc: R help <r-help at r-project.org>
Sent: Wednesday, September 25, 2013 11:46 AM
Subject: Re: [R] Computing calculation among two vectors
A cute problem. Is it homework?
Hint: ?outer
(will provide a much simpler solution than those given below)
-- Bert
On Wed, Sep 25, 2013 at 8:34 AM, arun <smartpink111 at yahoo.com> wrote:
Hi,
>You could also try:
>res1<-sapply(y,function(i) {x1<- expand.grid(x,x);fun1<- function(a,op,b){ f1<- match.fun(FUN=op); f1(a,b)};fun1(x1[,1],i,x1[,2])})
>row.names(res1)<- row.names(res)
> identical(res1,res)
>#[1] TRUE
>A.K.
>
>
>
>
>----- Original Message -----
>From: arun <smartpink111 at yahoo.com>
>To: R help <r-help at r-project.org>
>Cc:
>Sent: Wednesday, September 25, 2013 3:08 AM
>Subject: Re: Computing calculation among two vectors
>
>Hi,
>Try:
>x<- 1:4
> y<- c("*","/","-","+")
>res<-sapply(y,function(i) {x1<-expand.grid(x,x); unlist(lapply(paste0(x1[,1],i,x1[,2]),function(u) eval(parse(text=u))))})
>row.names(res)<- as.character(interaction(expand.grid(x,x),sep="_"))
>
>head(res)
># * / - +
>#1_1 1 1.0 0 2
>#2_1 2 2.0 1 3
>#3_1 3 3.0 2 4
>#4_1 4 4.0 3 5
>#1_2 2 0.5 -1 3
>#2_2 4 1.0 0 4
>
>
>A.K.
>
>
>
>I have two vectors one numeric and another with operand.
>
>Eg: x - 1,2,3,4 and y-"*", "/", "-", "+"
>
>I need to calculate all the possible two combinations in x with
>each of operand in y. As example, 1*2, 1/2, 1-2, 1+2, 1*3, 1/3....
>
>Any help appreciated.
>
>Regards
>Hussain
>
>______________________________________________
>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.
>
--
Bert Gunter
Genentech Nonclinical Biostatistics
Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm
More information about the R-help
mailing list