Reputation: 795
I am trying to populate data frame through loop. I succeeded for a certain extent but not able to bind that loop within a function
iterations = 34
variables = 6
v_log <- matrix(ncol=variables, nrow=iterations)
for (i in 1:34)
{
v_log[i,]<-c(1,"c1", "c2","c3", "c4", "c5")
}
v_log1=as.data.frame(v_log)
but when I am trying to bind them within the function,
f1<- function() {
iterations = 34
variables = 6
v_log <- matrix(ncol=variables, nrow=iterations)
for (i in 1:34)
{
v_log[i,]<-c(1,"c1", "c2","c3", "c4", "c5")
}
v_log1=as.data.frame(v_log)
}
On the execution of function, like f1() nothing will populate.
Please help.
Upvotes: 1
Views: 687
Reputation: 263481
It looks like it should produce a result. You need to assign the output of f1 to a named object or it will just be garbage collected. Welcome to functional programming. You have left the SAS/SPSS macro-processor domain:
> test <- f1()
> str(test)
'data.frame': 34 obs. of 6 variables:
$ V1: Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
$ V2: Factor w/ 1 level "c1": 1 1 1 1 1 1 1 1 1 1 ...
$ V3: Factor w/ 1 level "c2": 1 1 1 1 1 1 1 1 1 1 ...
$ V4: Factor w/ 1 level "c3": 1 1 1 1 1 1 1 1 1 1 ...
$ V5: Factor w/ 1 level "c4": 1 1 1 1 1 1 1 1 1 1 ...
$ V6: Factor w/ 1 level "c5": 1 1 1 1 1 1 1 1 1 1 ...
Upvotes: 1