Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R- How to run code for multiple values of same variable?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading