Create a dataframe looping a function's results

Hi there! So this is a simplification of my problem.
I have a dataframe like this:

df <- data.frame(name=c("lucas","julio","jack","juan"),number=c(1,15,100,22)) 

And i have a function that creates new values for every name, like this:

var_number <- function(x) {
example<- df %>% filter(name %in% unique(df$name)[x]) %>% 
select(-name) %>% mutate(
value1=number/2^5,
value2=number^5)
(example)}

var_number(1)
 0.03125 1

Now i have two new values for every name and i would like to create a loop to save each result in a new dataframe.
I know how to solve this particular problem, but i need a general solution that allows me to save the results of a function into a dataframe.
I;m looking for an automatic way to do something like this:

result<- bind_rows(var_number(1),var_number(2),var_number(3),var_number(4))

Since I would have to apply var_number around 1000 times and the lenght would change with every test i do.
There is anyway i can do something like this? I was thinking about doing it with "for", but i am not really sure about how to do it, I have just started with R and I am a total newbie.

Thank you!

Why not just do this?

library(dplyr, warn.conflicts = FALSE)

df <- data.frame(name = c("lucas", "julio", "jack", "juan"),
                 number = c(1, 15, 100, 22))

result <- df %>% 
  mutate(value1 = number / 2 ^ 5, value2 = number ^ 5) %>% 
  select(-name)

result
#>   number  value1      value2
#> 1      1 0.03125           1
#> 2     15 0.46875      759375
#> 3    100 3.12500 10000000000
#> 4     22 0.68750     5153632

Created on 2020-06-26 by the reprex package (v0.3.0)

library(tidyverse) # contains purrr library

#an arbitrary function that always outputs a dataframe
# with a consistent number of columns, in this case 3
myfunc <- function(x){
  data.frame(a=x*2,
             b=x^2,
             c=log2(x))
}

# iterate over 1:10 as inputs to myfunc, and
# combine the results rowwise into a df 
purrr::map_dfr(1:10,
               ~myfunc(.))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Hi, Sidd.
Thank you for your answer.
I know how to solve this particular problem, I made it easy to focus in the second part:

I need to create a data frame of n rows where row 1 is function(1), row 2 is function(2) and so on. The size of n is going to chage everytime and i am not sure about how to do so. I was thinking about doing it with a loop, but i am not really sure about how to.
Another way might be something like this:

result<- bind_rows(var_number(1),var_number(2)....,var_number(n))

There is any way to do that?

Thank you for your time!

That's it! That is an amazing solution!! Thank you so much for yout time! You saved my day!

1 Like