0

I want to replicate an expression using the replicate function in R. The expression is a multiplication containing lnorm distribution. The expression gives different results outside the replication function but when I insert it as an attribute into the replicate function it just replicates one result. It gives me e.g the same result many times.

d1 <- SumConcAcrylamide <- as.data.frame(SumConcAcrylamide)
d2 <- SumFoodIntakeBothDays <- as.data.frame(SumFoodIntakeBothDays)

library(data.table)

set.seed(123)

d3 <- setDT(d2)[(d1), Value_new :=
                  TotsumIntake_Perp*rnorm(n=1,d1$Loc, d2$Shape), on = "FoodCat"]
                    
#replicate this simulation 1000 times
                  
outcome <- replicate(n=2, {d3= setDT(d2)[(d1), Value_new :=
                                           TotsumIntake_Perp*rnorm(n=1,d1$Loc, d2$Shape), on = "FoodCat"]}, simplify = FALSE)
                                                                
### d3 if you run it many times you get a dataframe with different numbers for the Value_new column each time
                                                                
### When I run the outcome I get two times or as many times I set in the n=2,3.... attribute, the same numbers for the Value_new column
jblood94
  • 10,340
  • 1
  • 10
  • 15
MariaK
  • 1
  • 1
  • Why is there a bunch of stray backslashes in your code? – Roland Apr 06 '22 at 08:38
  • @Roland See [@meta](https://meta.stackoverflow.com/q/417243/6574038). – jay.sf Apr 06 '22 at 08:51
  • @jay.sf Thanks, I see. Well, I'm not cleaning that up. – Roland Apr 06 '22 at 11:28
  • @MariaK It's hard to be sure because I cannot read this malformed code example very well, but the key issue seems to be the assignment by reference (using `:=`) in your code. Each iteration of the `replicate` loop is overwriting the values stored in `Value_new` before `replicate` returns the result. Your code might work as expected if you change that part to `.(Value_new = TotsumIntake_Perp*rnorm(n=1,d1$Loc, d2$Shape))`. – Roland Apr 06 '22 at 11:30
  • Dear Roland, it actually worked, thank you!!!As I am kind of new to this, I would like to ask how did you suspect the : symbol in the syntax? Is there something that you could refer me to, so I can read? Thank you again. – MariaK Apr 07 '22 at 07:52
  • @MariaK https://cran.r-project.org/web/packages/data.table/vignettes/datatable-reference-semantics.html – Roland Apr 07 '22 at 08:30

0 Answers0