Search code examples
rloops

Making a Loop function and table in R


*How can I change the following code to compute D for various values of r and display all D values corresponding to r in a table?

library(powerSurvEpi)
r=seq(from = 0, to = 1,by=0.1)
D <- numDEpi.default(power = 0.8,
theta = 5.05,
p = 0.44,
rho2 = r*r,
alpha = 0.05)]

Solution

  • Good time for you to start learning tidyverse functionalities, then

    #load libraries
    library(powerSurvEpi)
    library(tidyverse)
    
    # create a function that returns the D for a given r
    foo = function(r){
      numDEpi.default(power = 0.8,
                      theta = 5.05,
                      p = 0.44,
                      rho2 = r*r,
                      alpha = 0.05)
    }
    
    # create a tibble with an r column containing different values for r
    df = tibble(
    r=seq(from = 0, to = 1,by=0.1)
    )
    
    # create a column D where it's values is the corresponding result from foo
    df |>mutate(
      D = foo(r)
    )