user330
user330

Reputation: 1290

How I can loop these data using a formula in R

I have the following arrays:

m <- c(1, 4, 7)
n <- c(2, 5, 8)
p <- c(3, 6, 9)
A <- seq(-2, 2, 0.1)

My Formula is:

(A+m)*(exp(p+n))  

I wnt to get the results for arrays. So m=1,n=2,p=3 for all possible A. m=4,n=5,p=6 for all possible A and m=7,n=8 and p=9 for all possible A. I want to use it when the numbers are increased in arrays.

The output is similar to this for the top and bottom three.

A   V1  V2  V3
-2  -148.41316  119748.3    120774764
-1.9    -133.57184  125735.7    123190259
-1.8    -118.73053  131723.1    125605754
-1.7    -103.88921  137710.5    128021250
-1.6    -89.0479    143697.9    130436745
-1.5    -74.20658   149685.4    132852240
…   ..  …   …
…   ..  ..  …

Upvotes: 1

Views: 58

Answers (1)

Valkyr
Valkyr

Reputation: 431

Using dplyr

library(dplyr)
df <- data.frame(A)
for(i in seq_along(m)){
  df <- df %>% 
    mutate(!!sym(paste0("V",i)) := sapply(A, function(x){(x+m[i])*(exp(p[i]+n[i]))}))
}

Output

> head(df)
     A         V1       V2        V3
1 -2.0 -148.41316 119748.3 120774764
2 -1.9 -133.57184 125735.7 123190259
3 -1.8 -118.73053 131723.1 125605754
4 -1.7 -103.88921 137710.5 128021250
5 -1.6  -89.04790 143697.9 130436745
6 -1.5  -74.20658 149685.4 132852240

Upvotes: 3

Related Questions