[R] odds ratio's and function

Wim Bertels wim.bertels at khleuven.be
Wed May 28 16:58:06 CEST 2008


Hallo,

i tried writing a function to extract 
all the odds ratio's from a ftable:
(+ p.adjust needs to build in)

So i tried the following:

ORCalcul <- function(m) {
or<-matrix(1:(length(m[,1])-1)*(length(m[1,])-1)*5,length(m[,1])-1,length(m[1,])-1)
	for(i in 1:length(m[,1])-1) {
		for(j in 1:length(m[1,])-1) {
			or[i,j,1] <- attr(m,"row.vars")[[1]][i]
			or[i,j,2] <- attr(m,"col.vars")[[1]][j]
			or[i,j,3] <- attr(m,"row.vars")[[1]][i+1]
			or[i,j,4] <- attr(m,"col.vars")[[1]][j+1]
			or[i,j,5] <-(m[i,j]*m[i+1,j1])/(m[i1,j]*m[i,j1])
		}	
	}
	ORCalcul <- c(or)
}

## which doenst work, because of the way R works with matrices,
## i am justed to other syntax, using the indices of a matrix
## so first question: i don't think there is way in R to work with
matrix m = new matrix(10,5,45) 
# m being a three dim matrix eg?

# so i tried, and tried, finally

ORCalcul <- function(m) {
	t
	for(i in 1:length(m[,1])-1) {
		for(j in 1:length(m[1,])-1) {
			row1 <- attr(m,"row.vars")[[1]][i]
			col1 <- attr(m,"col.vars")[[1]][j]
			row2 <- attr(m,"row.vars")[[1]][i+1]
			col2 <- attr(m,"col.vars")[[1]][j+1]
			or <- (m[i,j]*m[i+1,j+1])/(m[i+1,j]*m[i,j+1])
			ORCalculij <- c(row1, col1, row2, col2, or)
			append(t,ORCalculij)
		}	
		
	}
	ORCalcul <- t
	ORCalcul
}

# which unfornately only gives as output:, so doesnt work either
 [,1]
[1,]   NA

# the only variant i wrote that gave some output,
# but logically, only the last OR, is:

ORCalcul <- function(m) {
	for(i in 1:length(m[,1])-1) {
		for(j in 1:length(m[1,])-1) {
			row1 <- attr(m,"row.vars")[[1]][i]
			col1 <- attr(m,"col.vars")[[1]][j]
			row2 <- attr(m,"row.vars")[[1]][i+1]
			col2 <- attr(m,"col.vars")[[1]][j+1]
			or <- (m[i,j]*m[i+1,j+1])/(m[i+1,j]*m[i,j+1])
			ORCalcul <- c(row1, col1, row2, col2, or)
			# putting an append here, just gives me the code 			 # back..
		}	
		
	}
	ORCalcul
}




# what should i do? Suggestions?

(for the algoritmic logic, i need two more nested loops, that is not the
problem)

mvg,
Wim



More information about the R-help mailing list