user8548813
user8548813

Reputation:

Loop to compute ratios of each column with n other columns

I'm trying to create a function that will take a dataframe with x columns, and then output each column divided by every other column. So if this is my data

u<-c(0.05274095, 0.02516572, 0.01747562, 0.03370568, 0.02395228, 0.05950174)
s<-c(0.10016451, 0.18741220, 0.04703746, 0.11089235, 0.13629215, 0.22387265)
m<-c(0.2003734, 0.3691335, 0.3323357, 0.4613755, 0.3095862 ,0.3912790)

mydata<-cbind(u,s,m)

I want a column with u/s, u/m, s/u, s/m, m/u, m/s. I could do this simply by

opponent<-function(mydata){
U<-mydata["u"]
S<-mydata["s"]
M<-mydata["m"]


us<-(U/S)
um<-(U/M)

#etc for all divisions


resultsTable<-data.frame(taxa=rownames(mydata), channels=c(us,um))

return(resultsTable)  }

But I want the function to do this for n number of columns. Can I do this with a loop?

Upvotes: 1

Views: 468

Answers (1)

lmo
lmo

Reputation: 38500

Here is a method with combn which computes n-wise combinations of vectors. Then sapply loops through the pairs and returns a matrix of the ratios.

# get pairwise permutations
vars <- combn(colnames(mydata), 2)
vars <- cbind(vars, vars[2:1,])

# calculate the ratios for each pair
done <- sapply(seq_len(ncol(vars)), function(x) mydata[, vars[1, x]] / mydata[, vars[2, x]])
# add column names depicting ratios
colnames(done) <- paste(vars[1, ], vars[2, ], sep="/")

This returns

done
           u/s        u/m       s/m      s/u       m/u      m/s
[1,] 0.5265433 0.26321333 0.4998893 1.899179  3.799200 2.000443
[2,] 0.1342801 0.06817512 0.5077085 7.447123 14.668108 1.969634
[3,] 0.3715256 0.05258424 0.1415360 2.691605 19.017105 7.065341
[4,] 0.3039496 0.07305477 0.2403516 3.290020 13.688361 4.160571
[5,] 0.1757422 0.07736869 0.4402397 5.690154 12.925124 2.271490
[6,] 0.2657839 0.15206985 0.5721561 3.762456  6.575925 1.747775

Upvotes: 1

Related Questions