Search code examples
rloopslapplysapplymapply

Automating a multiplication process


I'm currently multiplying .6 by sqrt() of every unique pair of vi elements in my data below.

I'm new to R, but was wondering if there is a way to automate this process?

m = "
  study treatment focus_cat        yi        vi
1     1         1     type2 1.7581030 0.3947423
2     1         2     type1 1.9324494 0.8075765
3     1         3     type1 0.1225808 0.5933262
"
data <- read.table(text = m,h=T)

# How to automate the following and not repeat 3 lines of code:

.6 * sqrt(0.3947423*0.8075765)
.6 * sqrt(0.3947423*0.5933262)
.6 * sqrt(0.8075765*0.5933262)

Solution

  • You can use combn like (Thanks to @r2evans for helping simplifying my first approach!)

    .6 * sqrt(combn(data$vi, 2, prod))
    #[1] 0.3387661 0.2903721 0.4153267