sgt Fury
sgt Fury

Reputation: 170

Create data frame from function in R

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?

Upvotes: 1

Views: 11526

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 146224

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)

Upvotes: 2

vpipkt
vpipkt

Reputation: 1717

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".

Upvotes: 0

Related Questions