Texas
Texas

Reputation: 913

Preserving data structure when returning values from function in R

I currently have a basic script written in R, which has two functions embedded within another:

FunctionA <- Function() {
  results_from_B <- FunctionB()
  results_from_C <- FunctionC()
}

Function B generates some data which is then analysed in Function C.

If I stop the code within function A, I can see the structure of results_from_C - this appears under 'values' and I can refer to different elements using the syntax results_from_C$column_name1.

I achieved this within Function C by specifying the returned values using:

return(list(column_name_1 = value1, column_name_2 = value2)

However, I cannot work out how I can return these same values (in the same structure) from Function A - everything I try returns a list which is formatted as 'Data' rather than 'Values' and cannot be indexed using the syntax results_from_A$column_name1.

Can anyone help me to understand what I need to do in order to extract results from Function C outside of Function A?

Thanks in advance

Upvotes: 0

Views: 55

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

I don't understand what you mean by formatted as 'Data' rather than 'Values'. There's nothing wrong with the setup you describe, I every now and then use functions inside functions, it's perfectly OK.

(Note that R is case sensitive, it's function not Function.)

FunctionA <- function() {
  FunctionB <- function() 1:2*pi
  FunctionC <- function(x) 
      list(column_name_1 = x[1], column_name_2 = x[2])

  results_from_B <- FunctionB()
  results_from_C <- FunctionC(results_from_B)
  results_from_C
}

result <- FunctionA()
result
$column_name_1
[1] 3.141593

$column_name_2
[1] 6.283185

result$column_name_1
[1] 3.141593

Is this it? If not, please clarify your question.

Upvotes: 1

Related Questions