August 28, 2018

Sreekanth B

R Programming language Basic Freshers Interview Questions and Answers

Why should you adopt R programming language?

R programming language is best for statistical, data analysis and machine learning. By using this language we can create objects, functions, and packages.R is an open source programming language.
By using R we can create any form of statistics and data manipulation. Furthermore, it can be used in almost every field of finance, marketing, sports etc. R Programming is extensible and hence, R groups are noted for its energetic contributions.
Lots of Rs typical features can be written in R itself and hence, R has gotten faster over time and serves as a glue language.

What are programming features of R?

Packages are part of R programming. Hence, they are useful in collecting sets of R functions into
a single unit.
R’s programming features include database input, exporting data, viewing data, variable labels,
missing data, etc.
R is an interpreted language. So we can access it through command line interpreter.
R supports matrix arithmetic.
R supports procedural programming with functions and object-oriented programming with
generic functions. Procedural programming includes procedure, records, modules, and
procedure calls while object-oriented programming language includes class, objects, and
functions.


What are the applications of R?

Many data analysts and research programmers use R because R is the most prevalent language. Hence, R is used as a fundamental tool for finance.
Many quantitative analysts use R as their programming tool. Hence, R helps in data importing and cleaning, depending on what manner of strategy you are using on.
R is best for data Science because it gives a broad variety of statistics. In addition, R provides the environment for statistical computing and design. Rather R considers as an alternate execution of S.

Compare R with other technologies.

Data handling Capabilities – Good data handling capabilities and options for parallel computation.
Availability / Cost – R is an open source and we can use it anywhere.
Advancement in Tool –  if you are working on latest technologies, R gets latest features.
Ease of Learning – R has a learning curve. R is a low-level programming language. As a result, simple procedures can take long codes.
Job Scenario – It is a better option for start-ups and companies looking for cost efficiency.
Graphical capabilities – R is having the most advanced graphical capabilities. Hence, it provides us advanced graphical capabilities.
Customer Service support and community – R is the biggest online growing community.

Why is R Important?

R is a leading tool for machine learning, statistics, and data analysis. It is a programming language. By using R we can create objects, functions, and packages. R language is a platform independent so we can use it on any operating systems. The installation of R is free so we can use it without purchasing a license. R is not only statistic package and is an open source. It means anyone can examine the source code to see what exactly is doing on screen. Anyone can add a feature and fix bugs without waiting for the vendor to do this. Thus, it allows you to integrate with other languages (C, C++). It also enables you to interact with many data sources and statistical packages (SAS, SPSS). R has large growing community of users.

Is R is a slow language?

R programs can be slow, but well-written R programs are usually fast enough.
Speed was not the primary design criteria.
Designed to make programming easier.
Slow programs often a result of bad programming practices or not
understanding how R works.
There are various options for calling C or C++ functions from R.

Explain main features to write R code that runs faster?

R is a popular statistical software which is famous for the enormous amount of packages. R’s syntax is very flexible with making it convenient at the cost of performance. R is indeed slow compared to many other scripting languages, but there are a few tricks which can make our R code run faster.

Use matrix instead of data frame whenever possible. Actually data frame cause problem in many cases. Only use data frame when necessary.
Use double(n) to create a vector of length n instead of using code rep(0,n), and similar to others.
Split big data object (e.g., big data frame or matrix) to smaller ones, and operate on these smaller objects.

Use for each(i=1:n) %dopar% {} to do parallel computing if applicable. Even if a for loop is not parallelizable, for each(i=1:n) %do% {} is a better alternative.
Use vector and matrix operation if possible. Theses *apply functions are very helpful for this purpose.
Avoid changing the type and size of an object in R. Though we use R object as if they are typeless, they have type actually. In R, changing the type and size of an R object forces it to reallocate a memory space which is of course insufficient.
Avoid creating too many objects in each working environment. Not having enough memory can not only make your code run slower but also make it fail to run if have to allocate big vectors. One way to do this is to write small functions and run your functions instead of running everything directly in a working environment.

What is SAS and SPSS in R?

SAS stands for Statistical Analysis System. It was primarily developed to be able to analyze large quantities of agriculture data while SPSS stands for Statistical Package for the Social Sciences and was developed for the social sciences and was the first statistical programming language for the PC.

Why is R important for data science?

We can run your code without any Compiler – R is an interpreted language. Hence we can run Code without any compiler. R interprets the Code and makes the development of code easier.
Many calculations done with vectors – R is a vector language, so anyone can add functions to a single Vector without putting in a loop. Hence, R is powerful and faster than other languages.
Statistical Language- R used in biology, genetics as well as in statistics. R is a turning complete
a language where any type of task can be performed.

Explain What is R?

R is a language and environment for statistical computing and graphics. It is an open source programming language. R provides a wide variety of statistical and graphical techniques and is highly extensible. Data miners use it for developing statistical software and data analysis. One of the R’s strengths is the ease with which well-designed publication-quality plots can be produced, including mathematical symbols and formulae where needed. R is available as Free Software under the terms of the Free Software Foundation’s GNU General Public License in source code form. It compiles and runs on a wide variety of UNIX platforms and similar systems (including FreeBSD and Linux), Windows and MacOS. The R command line interface(CLI) consist of a prompt, usually the > character.

What is GUI in R?

GUI stands for Graphical User Interfaces. R is a command line driven program. The user enters commands at the prompt ( > by default ) and each command is executed one at a time. There have been a number of attempts to create a more graphical interface, ranging from code editors that interact with R, to full-blown GUIs that present the user with menus and dialog boxes.

What is CLI in R?

CLI stands for Command Line Interface. In a command line interface, you type commands that you want to execute and press return. For example, if you type the line 2+2 and press the return key, R will give you the result [1] 4

What is data mining and what data miners do in R?

R and Data Mining introduces researchers, post-graduate students, and analysts to data mining using R, a free software environment for statistical computing and graphics.

Who and When R discovered?

R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team, of which Chambers is a member. R is named partly after the first names of the first two R authors and partly as a play on the name of S.The project was conceived in 1992, with an initial version released in 1995 and a stable beta version in 2000.

Why is R Good for business?

The most important reason why R is good for business is that it is an open source. R is great for visualization. As per new research, R has far more capabilities as compared to earlier tools.
For data-driven business, data science talent shortage is a very big problem. Companies are
using R programming as their platform and recruit trained users of R.

What is Visualization in R?

Visualization is any technique for creating images, diagrams, or animations to communicate a message. Visualization through visual imagery has been an effective way to communicate both abstract and concrete ideas since the dawn of humanity.

What are R topical programming and statistical relevance?

a) Statistical

R is free, open source software.
R is available from free software Foundation.
b) Programming

Data inputs such as data type, importing data, keyboard typing.
Data Management such as data variables, operators.

What are statistical and programming features of R?

a) Statistical Features-

Basic Statistics: Mean, variance, median.
Static graphics: Basic plots, graphic maps.
Probability distributions: Beta, Binomial.

b) Programming Features-

Distributed Computing: Distributed computing is an open source, high-performance platform for the R language. It splits tasks between multiple processing nodes to reduce execution time and analyze large datasets.
R packages – R packages are a collection of R functions, compiled code and sample data. By default, R installs a set of packages during installation.

What are the advantages of R?

R is the most comprehensive statistical analysis package as new technology and ideas often appear first in R.
R is open-source software. Hence anyone can use and change it.
R is an open source. We can run R anywhere and at any time, and even sell it under conditions of the license.
R is good for GNU/Linux and Microsoft Windows. R is cross-platform which runs on many operating systems.
In R, anyone is welcome to provide bug fixes, code enhancements, and new packages.

What are Descriptive analysis methods in R?

Observation Method – There are two ways to draw the meaningful conclusion: Artificial & Natural.
Survey Method – In this method, questionnaires prepares and given to the participants. Hence After receiving the answers, the research preceded and results concluded.
Case Method – It involves a deep study of all the problems discussed. Thus, it makes us understand a particular situation.

What is R studio and how to use it?

a) USING RSTUDIO

step 1: Download and install Rstudio.
step 2: Open RStudio and do this:
step 3: Click on the menu: File -> New -> R Script
step 4: Paste the code in the new source code area
step 5: Click the “Source” button above the code area:

We can also use the console in RStudio. If we click “Run” instead of “Source” user input might not work properly. We can use the R documentation like this: help(function.name).

Using the R console – Running the r program on the command line or elsewhere will start the console. we can paste your code there.
Problems with this approach – If we use source(“filename.r”) to run your code then it will surely work. But If we paste the code some of it might be read as user input.
Running a source file with R – We can run a source file like this: r -f filename.r.
R also provides a lot of other command line arguments

What are R data types?

In programming, a data type is a classification that specifies what type of a value variable has. It also describes what type of relational, mathematical and logical operations can apply to it without causing an error. We need to use various variables to store information while doing programming in any programming language. Variables are nothing but reserved memory locations to store values. This means that when we create a variable we reserve some space in memory. The variables are assigned with R-Objects. Thus, the data type of the R-object becomes the data type of the variable.

How many types of data types are provided by R?

There are 5 types of data types present in R:

Integer data type
Numeric data type
Character data type
Complex data type
Logical data type

What is the main difference between an Array and a matrix?

A matrix is always two dimensional as it has only rows and columns. But an array can be of any number of dimensions and each dimension is a matrix. For example, a 3x3x2 array represents 2 matrices each of dimension 3×3.

What is R vector?

The basic data structure in R is the vector. It comes in two parts: atomic vectors and lists. They have three common properties:

Type function, what it is?

Length function, how many elements it contains.
Attribute function, extra arbitrary metadata. They differ in the types of their elements: All elements of an atomic vector must be the same type, whereas the elements of a list can have different types.

How many types of vectors are present in R?

Atomic Vector
Combining Vector
Vector arithmetic
Logical index vector
Numeric index
Duplicate Index
Range Indexes
Out-of-order Indexes
named Vectors Members

What is an Atomic vector and how many types of atomic vectors are present in R?

The atomic vector is the simplest R data type. Atomic vectors are linear vectors of a single primitive type, like an STL Vector in C++. There are four types of atomic vectors are present in R:

Numerical datatype
Integer datatype
Character datatype
Logical datatype

What are the disadvantages of R?

In R, quality of some packages is less than perfect.
In R, no one to complain, if something doesn’t work.
R is a software Application that many people devote their own time to developing.
R commands give little thought to memory management, and so R can consume all available memory.

Why R language?

In R, quality of some packages is less than perfect.
In R, no one to complain, if something doesn’t work.
R is a software Application that many people devote their own time to developing.
R commands give little thought to memory management, and So R can consume all available memory.

What is Predictive Analysis in R?

Predictive analysis is the branch of advanced analysis. It used to make predictions about unknown future events. The Predictive analysis contains data collection, statistics, and deployment. It uses many techniques from data mining, statistics, machine learning and analyzes current data to make predictions about future. It also allows the business users to create Predictive intelligence.

What is Predictive analysis process in R?

Define Project – It includes Project outcomes, business objectives, deliverables, scoping of the effects.
Data Collection – For predictive analysis, it collects data from different sources to analysis. Thus it provides a complete view of customer interactions.
Data Analysis – It is the process of cleaning, transforming, inspecting and modeling data. The goal of this process is to discover useful information.
Statistics – This process enables to confirm the assumptions. Hence it uses the assumption to test using a statistical model.
Modeling – An accurate predictive model about future is been created using predictive modeling. There are also options to choose the best model.
Deployment – To deploy the analytical results into everyday decision-making.
Model Monitoring – To ensure that it is providing an expected result, we have to manage model.

What is the need for Predictive Analysis in R?

Secure a competitive Stronghold It helps you to play your competitors’ weaknesses and company’s strengths. Hence, it allows you to check the actions of consumers and your competitors’ marketing and sales.
Do more than evaluating the past Employee analysis helps to check your company details. It will summarize past failure or past success. Therefore, the most important thing is that predictive analysis helps in learning from past experiences.
Maintain business integrity by managing fraud, First of all, Fraud investigators can look into only a set number of cases each week. Secondly, they use company’s past experience to score transactions according to their level of risk.
Advance your core business Capability The next step to growth is to improve company core offering. Thus At its core, it focuses on using it to optimize your approach to the market.

What is Descriptive analysis in R?

It does exactly what the name Implies “Describe”. it allows us to learn from our past and to understand how they might influence future outcomes. The main goal of is to find out the reasons behind previous success or failure in the past. Hence, Most of the social analysis is descriptive analysis. For Example – the company’s production, financials, operations, sales, finance, inventory, and customers.

What is recycling of elements in an R vector? Give an example.

When two vectors of different length are involved in an operation then the elements of the shorter vector are reused to complete the operation. This is called element recycling.

Example – v1 <- c(4,1,0,6) and v2 <- c(2,4) then v1*v2 gives (8,4,0,24). The elements 2 and 4 are repeated.

What is R lists?

Lists are the object which Contains elements of different types – like strings, numbers, vectors and another list inside it. A list can also contain a matrix or a function as its elements. The List is created using list() Function. In other words, a list is a generic vector containing other objects. For Example, The variable x is containing copies of three vectors n, s, b and a numeric value 3.
n = c(2, 3, 5)
s =  c(“aa”,  “bb”,  “cc”,  “dd”, “ee” )
b = c(TRUE,  FALSE,  TRUE,  FALSE,  FALSE )
x = list( n, s, b, 3)        # x contains copies of n, s, b)

Explain how to create a list in R?

Create a list containing string, numbers, vectors and logical values. For Example:

List_data <- list("Green", "Yellow", c(5,6,7), TRUE, 51.2)

print(list_data) When we execute the above code, it produces the following result-

[[1]]
[1] “Green”
[[2]]
[1] “Yellow”
[[3]]
[1] 5, 6, 7
[[4]]
[1] TRUE
[[5]]
[1] 51.2


How to use sapply in R?

Multipy all values by 10:

> sapply(BOD,function(x) 10 * x)
Time demand
[1,] 10 80
[2,] 20 100
[3,] 30 190
Used for array, margin set to 1:

> x <- array(1:9) > sapply(x,function(x) x * 10)
[1] 10 20 30 40 50 60 70 80 90
Two dimension array, margin can be 1 or 2:

> x <- array(1:9,c(3,3)) > x
[,1]   [,2]   [,3]
[1,]      1      4      7
[2,]      2      5      8
[3,]      3      6      9
> sapply(x,function(x) x * 10)
[1] 10 20 30 40 50 60 70 80 90
sapply: returns a vector, matrix or an array
# sapply : returns a vector, an array or matrix

sapply(c(1:3), function(x) x^2)
[1] 1 4 9

What is R matrices?

A matrix is a two-dimensional rectangular data set and thus it can be created using vector input to the matrix function. In addition, a matrix is a collection of numbers arranged into a fixed number of rows and columns. Usually, the numbers are the real numbers. By using a matrix function we can reproduce a memory representation of the matrix in R. Hence, the data elements must be of the same basic type.

How many methods are available to use the matrices?

There are so many methods to solve the matrices like adding, subtraction, negative etc.

What is control structure in R?

R has the standard control structures we would expect. expr can be multiple statements by enclosing them in braces { }. It is more efficient to use built-in functions rather than control structures whenever possible. These allow us to control the flow of execution of a script typically inside of a function. Control structures define the flow of the program. The decision is been based on the evaluation of a variable.

How many control statements are present in R?

There are eight control statements are present in R.

Name all control statements present in R?

If
If-else
For
Nested loops
While
Repeat and break
Next
return.

Explain how to access list elements in R?

Create a list containing a vector, a list and a matrix.

list_data <- list(c("Feb","Mar","Apr"))
list("white",13.4)), matrix(c(3,9,5,1,-2,8), nrow = 2)
For Example: Give names to the elements in the list:

Names(list_data) <- c(“1 st  Quarter”, “A Matrix”, “A Inner list”)

Access the first element of the list:

print(list_data[1])

Access the third element. As it also a list, all its elements will print:

Print(list_data[3])

By using the name of the element access the list elements:

Print(list_data$A Matrix)

It will produced the following result after executing the above code:

$”1 st  Quarter” [1] “Feb”, "Mar”, "Apr”
$A_Inner_list
$A_Inner_list[[1]]
[1] “White”
$A_Inner_list[[2]]
[1] 13.4
$ “A Matrix” [1]
[1]   [2]   [3]
[1]     3     5    -2
[2]     9     1     8

Explain how to manipulate list elements in R?

Create a list containing a vector, a matrix and a list.

list_data <- list(c("Feb","Mar","Apr"),
matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3))
For Example:

Give names to the elements in the list:

names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

Add element at the end of the list:

list_data[4] <- "New element"
print(list_data[4])
Remove the last element:

list_data[4] <- NULL # Print the 4th Element.print(list_data[4])

Update the 3rd Element:

list_data[3] <- "updated element"
print(list_data[3])
When we execute the above code, it produces the following result:

[[1]]
[1] "New element"
$NULL
$`A Inner list`
[1] "updated element"

Explain how to generate lists in R?

We can use a colon to generate a list of numbers. For example:

-3:3
[1] -3 -2 -1 0 1 2 3

Explain how to operate on lists in R?

R allows to Operate on all list values at once. For example:

c(1,3,5) + 4

This and the Apply function allow you to avoid most for loops.

[1] 5, 7, 9

What are features of R functions?

Function component describes the three main components of a function.

Lexical scoping teaches how R finds values from names.
In R, every operation is a function call.
Function arguments discuss the three ways of supplying arguments to a function. it shows to call
The function is given a list of arguments and to the impact of lazy evaluation.
Special calls describe two special types of function infix and replacement functions.
Return values discuss how and when functions return values. it also shows how you can ensure
that a function does something before it exists.

What is function definition?

An R function is been created using the keyword function. The basic syntax of an R function definition is as follows −
function_name <- function(arg_1, arg_2, …) {
Function body
}

What are the components of R functions?

The different parts of a function are −

Function Name − It is the actual name of the function because it stored in R environment as an object with this name.
Arguments − An argument is a placeholder. When a function invokes, we pass a value to the
argument. Arguments are optional; that is, a function may contain no arguments. Also, arguments can have default values.
Functions Body – In a function body, statements can be collected. and hence, it defines what the function does.
Return Value − the return value of a function is the last expression in the function body to check.

What are Generic Functions in R?

R has three object-oriented (OO) systems: [[S3]], [[S4]] and [[R5]]. … A method is a function associated with a particular type of object. S3 implements a style of object-oriented programming called generic-function OO.

What are R packages?

Packages are collections of R functions, data, and compiled code in a well-defined format. The directory where packages are stored is called the library. R comes with a standard set of packages. Others are available for download and installation. Once installed, they have to be loaded into the session to be used.

Name the functions which helps in importing data from other applications in R?

read.table()
readlines()
read.fwf
read.delim()
scan()
read.csv()
read.csv2()

What is more functions in R and name them?

We have to load the built-in foreign command to use these functions:

>library("foreign")

R more functions:

read.xpss
read.xport
read.dta

List out some of the function that R provides?

Mean
Median
Distribution
Covariance
Regression

What is the distribution in R?

R Functions for Probability Distributions. Every distribution that R handles has four functions. There is a root name, for example, the root name for the normal distribution is the norm. This root is prefixed by one of the letters. p for “probability”, the cumulative distribution function (c. d. f.)

What are vector functions?

In R, a function is a piece of code written to carry out a specified task. R Functions are called as objects because we can work with them exactly the same way we work with any other type of object. Vector functions are those functions which we used in vectors.
For Example: rep(), seq(), using all() and any(), more on c() etc.

Most common functions which we use in vector operations are –

rep()
seq()

Explain how to repeat vectors in R?

We can use the rep() function in several ways if we want to repeat the complete vector. For examples: specify the argument times 1. To repeat the vector c(0, 0, 7) three times, use this code:

> rep(c(0, 0, 7), times = 4)
[1] 0 0 7 0 0 7 0 0 7 0 0 7 2
We can also repeat every value by specifying the argument each, like this:

> rep(c(2, 4, 2), each = 2)
[1] 2 2 4 4 2 2 3
We can tell R for each value how often it has to repeat:

> rep(c(0, 7), times = c(4,3))
[1] 0 0 0 0 7 7 7 4
In seq, we use the argument length.out to define R. it will repeat the vector until it reaches that length, even if the last repetition is incomplete.

> rep(1:3,length.out=9)
[1] 1 2 3 1 2 3 1 2 3

How to create vectors in R?

a) To create a vector using integers:

For Example, We use the colon operator (:) in R.
The code 2:6 gives you a vector with the numbers 2 to 6, and 3:-4 create a vector with the numbers 3 to –4, both in steps of 1.

b) We use the seq() to make steps in a sequence.

Seq() function used to describe by which the numbers should decrease or increase.

For Example In R, the vector with a numbers 4.5 to 3.0 in steps of 0.5.

> seq(from = 4.5, to = 3.0, by = -0.5)
[1] 4.5 4.0 3.5 3.0 c
You can specify the length of the sequence by using the argument out. R calculates the step size itself. For Example We can make a vector of nine values going from –2.7 to 1.3 like this:

> seq(from = -2.7, to = 1.3, length.out = 9)
[1] -2.7 -2.2 -1.7 -1.2 -0.7 -0.2 0.3 0.8 1.3


Can we update and delete any of the elements in a list?

We can update any of the element but we can delete only the element at the end of the list.

How many types of object are present In R?

There are 6 types of objects present in R:

Vectors
Matrices
Arrays
Lists
Data Frames
Factors

What are R Functions?

A function is a piece of code written to carry out a specified task. Thus it can or can’t accept arguments or parameters and it can or can’t return one or more values. In R, functions are objects in their own right. Hence, we can work with them exactly the same way we work with any other type of object.

What is using all() and any()?

a) na.rm – State whether NA values should ignore.

b) any(…, na.rm=FALSE) … – One or more R objects that need to be check. na.rm – State whether NA values should ignore. The any() and all() functions are shortcuts because they report any or all their arguments are TRUE.

> x <- 1:10 > any(x > 5)
[1] TRUE
> any(x > 88)
[1] FALSE
> all(x > 88)
[1] FALSE
> all(x > 0)
[1] TRUE For Example: Suppose that R executes the following:
> any(x > 5)
It first evaluates x > 5:

(FALSE, FALSE, FALSE, FALSE, FALSE)

We use any() function – that reports whether any of those values are TRUE while all() function works and
reports if all the values are TRUE.

What is R’s C interface?

R’s source code is a powerful technique for Improving Programming skills. But, many base R function was already written in C. It is been used to figure out how those functions work. All functions in R defined with the prefix Rf_ or R_.

Outline of Rs C interface

Input Validations talks about itself so that C function doesn’t crash R.
C data Structures shows how to translate data structure names from R to C.
Creating and modifying vectors teaches how to create, change, and make vectors in C.
Calling C defines the basics of creating. It also defines the functions with the inline package.

What are Prerequisites for R’s C interface?

We need a C compiler for C interface. Windows users can use Rtools. Mac users will need the Xcode command line tools. Most Linux distributions will come with the necessary compilers. In Windows, it is necessary to include Windows PATH environment variable in it:

Rtools executables directory (C:\Rtools\bin),
C compiler executables directory (C:\Rtools\gcc-4.6.3\bin).

How to call C function from R?

Generally, to call a C function it required two pieces:

C function.
R wrapper function that uses.Call().
The function below adds two numbers together:

// In C -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
#include <R.h>
#include <Rinternals.h>
SEXP add(SEXP a, SEXP b) {
SEXP result = PROTECT(allocVector(REALSXP, 1));
REAL(result)[0] = asReal(a) + asReal(b);
UNPROTECT(1);
return result;
}
# In R -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
add <- function(a, b) {
.Call("add", a, b}
}

What are R matrices and R matrices functions?

A matrix is a two-dimensional rectangular data set. Thus it can create using vector input to the matrix function. Also, a matrix is a collection of numbers arranged into a fixed number of rows and columns. Usually, the numbers are the real numbers. We reproduce a memory representation of the matrix in R with the matrix function. Hence, the data elements must be of the same basic type. Matrices functions are those functions which we use in matrices.
There are two types of matrices functions:

apply()
sapply()

What is apply() function in R?

Return a vector or array or list of values obtained by applying a function to margins of an array or matrix.

Keywords
array, iteration

Usage

apply(X, MARGIN, FUN, …)

Arguments

X – an array, including a matrix
… – optional arguments to FUN
FUN – The function to apply: see ‘Details’
MARGIN -Functions will apply on subscripts in a vector.

What is the apply() family in R?

Apply functions are a family of functions in base R. which allow us to perform an action on many chunks of data. An apply function is a loop, but run faster than loops and often must less code. There are many different apply functions. The called function could be:

There is some aggregating function. They include meaning, or the sum(includes return a number or scalar);
Other transforming or subsetting functions.
There are some vectorized functions. They return more complex structures like lists, vectors, matrices, and arrays.
We can perform operations with very few lines of code in apply().

What is sapply() in R?

A Dimension Preserving Variant of “sapply” and “lapply”
sapply is a user-friendly version. It is a wrapper of lapply. By default sapply returning a vector, matrix or an array.

Keywords
Misc, utilities

Usage

Sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
Lapply(X, FUN, ...)
Arguments

X – It is a vector or list to call sapply.
FUN – a function.
… – optional arguments to FUN.
simplify – It is a logical value which defines whether a result is been simplified to a vector or
matrix if possible?
USE.NAMES – logical; if TRUE and if X is a character, use X as names for the result unless it had names already.

Subscribe to get more Posts :