Home > Software design >  R loop question- looping through a dataframe
R loop question- looping through a dataframe

Time:04-24

I am new to R and need some help figuring out a problem. In summary, I have a dataframe with different values : 10 rows and 6 columns. Each column represents a variable: column 1- n1, column2- mean1, column3- varaince1, column4- n2, column5- mean2, column6- variance2. Each row is a different combination of these variables. I want to iterate through each row and generate two samples- sample 1- random normal variables with n1,mean1 and sd1 (variance1 sqrt) and sample 2-random normal variables with n1,mean1 and sd1 (variance1 sqrt). Can someone let me know what would be the best way to proceed? Thanks for the help.

Here is a sample data I have using the dput() function:

structure(list(n1 = c(5, 10, 5, 10, 5, 10), n2 = c(3, 3, 6, 6, 
3, 3), mean1 = c(4, 4, 4, 4, 6, 6), mean2 = c(15, 15, 15, 15, 
15, 15), sd1 = c(1, 1, 1, 1, 1, 1), sd2 = c(10, 10, 10, 10, 10, 
10)), out.attrs = list(dim = c(n1 = 2L, n2 = 2L, mean1 = 2L, 
mean2 = 2L, sd1 = 2L, sd2 = 2L), dimnames = list(n1 = c("n1= 5", 
"n1=10"), n2 = c("n2=3", "n2=6"), mean1 = c("mean1=4", "mean1=6"
), mean2 = c("mean2=15", "mean2=20"), sd1 = c("sd1=1", "sd1=5"
), sd2 = c("sd2=10", "sd2= 4"))), row.names = c(NA, 6L), class = "data.frame")

CodePudding user response:

You can save the data generated in lists. params is the data frame of parameters.

data1<-list()
data2<-list()
for(i in 1:dim(params)[1]){
  data_1i<- rnorm(n= params$n1[i], mean= params$mean1[i], sd=params$sd1[i] )
  data_2i<- rnorm(n= params$n2[i], mean= params$mean2[i], sd=params$sd2[i] )

  data1[[i]]<- data_1i
  data2[[i]]<- data_2i
}

CodePudding user response:

You did not indicate how you plan to use the results. This will store both sets of random numbers in a list:

set.seed(42)   # For reproducibility
results <- apply(params, 1, function(x) list(first=rnorm(x[1], x[3], x[5]),
           second=rnorm(x[2], x[4], x[6])))
    results[[1]]
    # $first
    # [1] 5.370958 3.435302 4.363128 4.632863 4.404268
    # 
    # $second
    # [1] 13.93875 30.11522 14.05341
    # 
    results[[1]]$first
    # [1] 5.370958 3.435302 4.363128 4.632863 4.404268
    results[[1]]$second
    # [1] 13.93875 30.11522 14.05341
  • Related