[R] Computing calculation among two vectors

arun smartpink111 at yahoo.com
Wed Sep 25 09:08:57 CEST 2013


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