1

I have programmed one function, which can create a data frame: (This function modifies the global environment! )

abc=function(x,y) {
   if(y>=11)
    stop("Noooooooooooooooooooooooooope!")
     value = NA
  for (i in 1:10) {
    a=2+i
    b=3
    value[i]=(x+a)*(b*y)
  }
  df=data.frame(ID=(1:10),Value=(value)) 
  assign("df",df,envir = .GlobalEnv)
  View(df)
}
abc(2,9)

This function create a data frame like this:

    ID  Value
1   1   135
2   2   162
3   3   189
4   4   216
5   5   243
6   6   270
7   7   297
8   8   324
9   9   351
10  10  378

But now I need to create a "big" data frame in which will be more columns. For arguments abc(1,9), abc(2,9), abc(3,9) .... abc(13,9). The new data frame will be look like this:

    ID  Value1  Value2 Value3 ...
1   1   108 135 ...
2   2   135 162 ...
3   3   162 189 ...
4   4   189 216 ...
5   5   216 243 ...
6   6   243 ... ...
7   7   270 ... ...
8   8   297 ... ...
9   9   324 ... ...
10  10  351 ... ...

How I can make it?

sgt Fury
  • 170
  • 1
  • 7

2 Answers2

2

Not the most elegant, but not too bad:

First I modified your function because I found the View annoying and it's much better to return a something explicitly rather than just stick it in the global environment:

abc=function(x,y) {
    if(y>=11)
        stop("Noooooooooooooooooooooooooope!")
    value = NA
    for (i in 1:10) {
        a=2+i
        b=3
        value[i]=(x+a)*(b*y)
    }
    df=data.frame(ID=(1:10),Value=(value)) 
    #assign("df",df,envir = .GlobalEnv)
    #View(df)
}

Now to run it for x = 1:13 and combine the results:

dflist = lapply(1:13, abc, y = 9)
for (i in seq_along(dflist)) {
    names(dflist[[i]])[2] = paste0("Value", i)
}
bigdf = Reduce(function(...) merge(..., all = T), dflist)

(using the method from this answer)

Community
  • 1
  • 1
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 1
    thank you for your answer. I look at your method! Many thanks! But yes it is working! Thank you! I cant rate your comment (up) cause I have 14 reputation. But in future, I would like to "up" it! – sgt Fury Jan 06 '15 at 16:34
0

You could remove the ID column from your function's data frame, and instead of the assign call, just return the value vector. Then proceed in this way:

df<- data.frame(ID=1:10, Value1=abc(1,9), Value2=abc(2,9), Value3=abc(3,9))

Of course this may be inefficient or not feasible depending on your definition of "big".

vpipkt
  • 1,710
  • 14
  • 17