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?

1
  • 1
    Please warn people if you post a function that modifies the global environment Commented Jan 6, 2015 at 16:21

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

Thank you for your answer! Yes it is good solution. I will use this. Many thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.