Home > Back-end >  R- How to run code for multiple values of same variable?
R- How to run code for multiple values of same variable?

Time:01-03

Let's say I am running some formulas in R, and I have a variable k. In my actual case, it is a taxation level, but for the purpose of this example, it can only be 2 or 3. I want to create a code which runs the formulas for both values of the variable (k = 2, k = 3) and puts the output for both cases in a table (I like using knitr's kableExtra package). For the purposes of efficiency, I do not want to copy and paste the formulas (in the real case it is quite a lengthy block).

How could I do this?

> k equals 2 *and* 3
> "if" does not refer to an if statement. It is just an explanatory placeholder. 

k <- 2 
firstvariable = k*100
secondvariable = firstvariable/2

data1 <- data.frame(secondvariable (if k = 2), firstvariable (if k = 1))

library(kableExtra)
table <- kbl(data1, caption = "Both values") 
table

CodePudding user response:

This is a case for sapply(). The sapply() function allows you to run the same function over every element in a vector. If that function returns two values, then sapply() creates a matrix that you can easily turn into a table.

k <- c(2,3)
my_fun <- function(x) {
  c(firstvariable = x * 100, secondvariable = x * 50)
}
sapply(k, my_fun)

               [,1] [,2]
firstvariable   200  300
secondvariable  100  150

You can then use cbind() to assemble your data frame. You will need to transpose your matrix with t() first.

cbind(data.frame(k), t(sapply(k, my_fun)))

  k firstvariable secondvariable
1 2           200            100
2 3           300            150

Now you can go and do whatever you want.

CodePudding user response:

Since multiplication is vectorised you can directly perform this calculation on the vector.

create_data <- function(k) {
  tibble::tibble(k, firstvariable = k * 100, secondvariable = firstvariable/2)  
}

result <- create_data(c(2, 3))
result
# A tibble: 2 x 3
#      k firstvariable secondvariable
#  <dbl>         <dbl>          <dbl>
#1     2           200            100
#2     3           300            150
  •  Tags:  
  • r
  • Related