My code:
V_max=15
H=1
n=1
C=c(0,0.01,0.1,1)
fun <- function( C, H, n ){
2 / (3 (C / H)^n)
}
for(i in 1:length(C)){
V_C <- V_max*fun(C[i],H,n)
x3 <- rnorm(1000,V_C,1)
}
I want my loop to iterate over all the values of vector C and calculate the means for each iteration successively and that the means are save as one data.frame. Since these are my beginnings in R, I am asking for help
CodePudding user response:
You already got the right clue from Paul Stafford Allan but since you siad you are new to R, I included his tip in your original code:
V_max=15
H=1
n=1
C=c(0,0.01,0.1,1)
fun <- function( C, H, n ){
2 / (3 (C / H)^n)
}
# generating empty vector
means_vec <- vector()
for(i in 1:length(C)){
V_C <- V_max*fun(C[i],H,n)
x3 <- rnorm(1000,V_C,1)
# saving value in empty vector in each iteration
means_vec[i] <- mean(V_C)
}
CodePudding user response:
I modified your question for an easy solution. Since your V_max, H,n is constant i have added the same as constant in function than as variable. Your initial function is modified by incorporating V_max.
V_max=15
H=1
n=1
C=c(0,0.01,0.1,1)
fun <- function( C){
V_max*(2 / (3 (C / H)^n))
}
fun2<-function(x){
rnorm(1000,x,1)
}
library(tidyverse)
V_C<-map(C,fun) ## can use map_dbl(C,fun)
df_list<-map(V_C,fun2)
Hope this helps. Ps: These are preliminary steps towards tidyverse.