How to create a data frame with results from a function

Asked

Viewed 170 times

1

I created a function and would like to create a data frame with results of this function for a few hundred parameters values. I did as in the script below, but as we can see the script will be giant in case it has hundreds of values. How can I make a cleaner script to achieve what I want?

z <- data.frame(k=c(runif(10, min=0, max=1)), 
              g=c(runif(10, min=0, max=1)), 
              h=c(runif(10, min=0, max=1)))
z

F <- function(t){
  k <- z$k
  g <- z$g
  h <- z$h
  l <- t*k+g+h  
  return(l)
}

oc1 <- F(1)
oc2 <- F(2)
oc3 <- F(3)

Tabela_final <- data.frame(Munic=c(1,2,3), 
                           FatorOP=c(oc1, oc2, oc3))

Tabela_final
  • Which part do you want to replace?

1 answer

3

If what you want to simplify is the process of merging the results of the function into a vector to form a columna in Tabela_final, then you can use lapply with do.call to form a vector.

z <- data.frame(k=c(runif(10, min=0, max=1)), 
                g=c(runif(10, min=0, max=1)), 
                h=c(runif(10, min=0, max=1)))

fun_a <- function(t){
  k <- z$k
  g <- z$g
  h <- z$h
  l <- t*k+g+h  
  return(l)
}

# vetor com input para fun_a
vec <- c(1:3)

# use lapply com do.call para juntar o resultado de cada iteração
res_col <- do.call(c, lapply(seq_along(vec), function(x){
  fun_a(vec[[x]])
}))


Tabela_final <- data.frame(Munic = c(1:3), 
           FatorOP = res_col)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.