lundi 23 juillet 2018

How can I efficiently populate a data frame with an index variable and two random variables?

I have written a dataframe with 3 variables: x,y and z with the following characteristics:

1) The dataframe contains 10 sets of x and y variables drawn at random from a standard normal distribution. 2) Each set, denoted as z, has 10 observations of x, y pairs.

df1<-data.frame(x=rnorm(10),y=rnorm(10),z=1)
df2<-data.frame(x=rnorm(10),y=rnorm(10),z=2)
df3<-data.frame(x=rnorm(10),y=rnorm(10),z=3)
df4<-data.frame(x=rnorm(10),y=rnorm(10),z=4)
df5<-data.frame(x=rnorm(10),y=rnorm(10),z=5)
df6<-data.frame(x=rnorm(10),y=rnorm(10),z=6)
df7<-data.frame(x=rnorm(10),y=rnorm(10),z=7)
df8<-data.frame(x=rnorm(10),y=rnorm(10),z=8)
df9<-data.frame(x=rnorm(10),y=rnorm(10),z=9)
df10<-data.frame(x=rnorm(10),y=rnorm(10),z=10)

then I bind the rows in one dataframe

df<bind_rows(df1,df2,df3,df4,df5,df6,df7,df8,df9,df10)

I have tried to do this using the following for loop:

for (i in seq(1,10,1)) {
  df<-data.frame(x="",y="",z="")
  df<-rbind(data.frame(x=rnorm(10),y=rnorm(10),z=i))
}

but I am unable to make the z-index variable to increase each 10 rows and bind the data generated 10 times. The z variable remains constant and equal to 10

Is there anything I have to modify in the loop or other options to do this?




Aucun commentaire:

Enregistrer un commentaire