Open In App

Read RData Files in R

In this article we are going to see how to read R File using R Programming Language. We often have already written R scripts that can be reused using some simple code. Reading R Programming Language code from a file allows us to use the already written code again, enabling the possibility to update the code, keep the project clean, and share the base code without exposing the project. In this article, we will see a simple function source() that allows us to achieve these benefits.  Using the source() function we can read the R code from another file. It is implemented when accessing functions of other R scripts is required.

In this article, we will see some simple use cases of the source() function.



Syntax:

source(path/Desktop/somescript.R)

Parameters: Path to the R file that has functions that are to be used.



Features:

Example 1:

Suppose we want to convert a sequence of letters to lowercase, then this can be done using the following function.




# to_low.R
  
# function that converts
# sequence of letters to lowercase
# and prints them
print_letters <- function(letters)
for ( i in letters) {
   print(tolower(i))
}

Now let’s use source(“to_low.R”) to use the function print_letters in the main working file, considering both files are in the same directory. You can download these R files from the link provided here.




# source the file which contains
# the function to be called
source("to_low.R")
  
# LETTERS gives first three 
# alphabets in uppercase
alphas <- LETTERS[1:3]
  
# calling the function from
# another file > to_low.R
print_letters(alphas)

Output:

[1] "a"
[1] "b"
[1] "c"

Example 2:

Suppose we have a proportion of programming languages used. The bar_and_pie function in barpie.R file outputs the bar plot and pie chart.




# barpie.R
  
# function to output barplot and piechart
bar_and_pie <- function(x){
    y <- c("C++", "Java", "Python", "R")
    barplot(x, names.arg = y)
    pie(x, label = y, main = "Pie Chart")
}

Now we pass the x vector to the bar_and_pie function. It is achieved by sourcing the file which contains that function using source(‘barpie.R’):




# source the file which contains
# the function to be called
# assuming in same directory
source('barpie.R')
  
# Create a vector of pies
x <- c(10,20,30,40)
  
# pass the x to the function in barpie.R file
bar_and_pie(x)

Output:

Bar plot and pie chart


Article Tags :