Home > Software engineering >  Can I use the output of a function in another R file?
Can I use the output of a function in another R file?

Time:02-10

I built a function that retrieves data from an Azure table via a REST API. I sourced the function, so I can reuse it in other R scripts.

The function is as below:

Connect_To_Azure_Table(Account, Container, Key)

and it returns as an output a table called Azure-table. The very last line of the code in the function is

head(Azure_table) 

In my next script, I'm going to call that function and execute some data transformation.

However, while the function executes (and my Azure_table is previewed), I don't seem to be able to use it in the code to start performing my data transformation. For example, this is the beginning of my ETL function:

library(dplyr)
library(vroom)
library(tidyverse)
library(stringr)

#Connects to datasource

if(exists("Connect_To_Azure_Table", mode = "function")) {
source("ConnectToAzureTable.R")
}

Account <- "storageaccount"
Container <- "Usage"
Key <- "key"

Connect_To_Azure_Table(Account, Container, Key)

# Performs ETL process

colnames(Azure_table) <- gsub("value.", "", colnames(Azure_table))                # Removes prefix from column headers

warning

Both the function and the table get warning. But while the function executes anyway, the Azure_table throws an error:

> # Performs ETL process
> 
> colnames(Azure_table) <- gsub("value.", "", colnames(Azure_table))                # Removes prefix from column headers
Error in is.data.frame(x) : object 'Azure_table' not found

What should I be doing to use Azure_table in my script?

Thanks in advance!

~Alienvolm

CodePudding user response:

You can ignore the RStudio warnings, they are based on a heuristic, and in this case it’s very imprecise and misleading.

However, there are some errors in your code.

Firstly, you’re only sourceing the code if the function was already defined. Surely you want to do it the other way round: source the code if the function does not yet exist. But furthermore that check is completely redundant: if you haven’t sourced the code which defines the function yet, the function won’t be defined. The existence check is unnecessary and misleading. Remove it:

source("ConnectToAzureTable.R")

Secondly, when you’re calling the function you’re not assigning its return value to any name. You probably meant to write the following:

Azure_table <- Connect_To_Azure_Table(Account, Container, Key)
  • Related