jeudi 26 mai 2016

adding columns to dataframe in function called by for-loop

I am trying to build up a dataframe within my function myfunction by calling it within a for-loop.

It looks like this

df = data.frame("Indices" = c("a", "b"))

myfunction = function(i){
    df = cbind(df, as.data.frame(rbind(i,i^2)))
}

for(i in 1:10){
  myfunction(i)
}

My aim is to add one more column to the df through each iteration caused by the for-loop. But unfortunately df simply stays empty (i.e. no further columns are being added).

So, in the end it should look something like this:

Indices V1 V1 V1 V1 V1 V1 V1 V1 V1  V1
i       a  1  2  3  4  5  6  7  8  9  10
        b  1  4  9 16 25 36 49 64 81 100

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire