[R] Computing calculation among two vectors

arun smartpink111 at yahoo.com
Wed Sep 25 17:34:03 CEST 2013


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



More information about the R-help mailing list