Read RData Files in R
Last Updated :
13 Feb, 2023
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:
- Reusable: The functions can be used again and again without rewriting.
- Updation: Easy to update and maintain without touching the main script.
- Distribute: Functions can be used by anyone by sharing the script without exposing your main project.
Example 1:
Suppose we want to convert a sequence of letters to lowercase, then this can be done using the following function.
R
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.
R
source ( "to_low.R" )
alphas <- LETTERS [1:3]
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.
R
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’):
R
source ( 'barpie.R' )
x <- c (10,20,30,40)
bar_and_pie (x)
|
Output:
Bar plot and pie chart
Share your thoughts in the comments
Please Login to comment...