1

I have created a function, which computes the statistics on various patients data, and as well as outputting plots, it generates data frames containing summary statistics for each patient.

If i copy and run the function within R, the outputs are available to me. However, I am now calling the function from a separate R script, and the data frames are no longer available.

Is there any way to correct this?

For example,

test=function(a){
  A=a
  B=2*a
  C=3*a
  D=4*a
  DF=data.frame(A,B,C,D)
}

a=c(1,2,3,4)
test(a)

This does not return DF, yet if I were to type:

  a=c(1,2,3,4)
  A=a
  B=2*a
  C=3*a
  D=4*a
  DF=data.frame(A,B,C,D)

Then clearly DF is returned. Is there a simple way to fix this so that DF becomes available from the test function?

sym246
  • 1,836
  • 3
  • 24
  • 50
  • If `test(a)` is not returning the DF, maybe you should add a line like `return(DF)` inside the function. (Not sure if that's what you mean.) – Frank Mar 29 '16 at 14:57
  • That's not exactly what I meant, but i can see how it came across that way. I would like `DF` to be stored in the global environment as opposed to displayed in the console. – sym246 Mar 29 '16 at 14:59
  • If you add `return(DF)` inside the function and use the function like `DF = test(a)`, it should do as you expect. That's the idiomatic way to do things in R, rather than having functions create objects as side-effects. If you really want to do as you describe, there's the `<<-` assignment operator that might work, but it's usually discouraged. Related: http://stackoverflow.com/q/9726705/1191259 – Frank Mar 29 '16 at 15:05

2 Answers2

0

Try:

test=function(a){
  A=a
  B=2*a
  C=3*a
  D=4*a
  DF=data.frame(A,B,C,D)
}

a=c(1,2,3,4)
df<-test(a)
print(df)

By assigning the function's returned value to a new variable it is now accessible in the global space.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
0

If you want to assign an object from within a function to the global environment for easy retrieval then your operators are "<<-" or "->>" for more info see:

?assignOps() i.e.

test <- function(a)
       A=a
       B=2*a
       C=3*a
       D=4*a
       DF <<- data.frame(A,B,C,D)
}

# trial your dummy data
a=c(1,2,3,4)
test(a)
DF

Hey presto ... it works! Writing return(DF) within the function will not deliver your data frame to the global environment.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nathan
  • 646
  • 5
  • 10