if Statement in R: if-else, if-else-if Conditional Statement

General Introduction to if Statement in R

In R Language, the if statement(s) is a conditional control used for making a decision. The if statement in R is used to run the block of statements when a certain condition is met. Therefore, if statements are also called conditional statements.

if Statement in R

An if statement consists of a boolean expression followed by one or more statements. The basic syntax for creating a if statement is

if ( boolean expression ) {
      # statements 
      # these statements will execute only if the boolean expression is true
}

The code inside the brackets of the if statement will be executed if the boolean expression in parenthesis evaluates to be true. For example,

x <- 3.0L
if ( is.integer(x) ){
   print("x is an integer")
}

if-else Statement

An if statement can be followed by an optional else statement. The else statement executes only when the boolean expression in the parenthesis of the if statement evaluates to false. The basic syntax of a if-else statement is

if (boolean expression){
        # statement(s) will execute if the boolean expression is true 
}
else{
      # statemenet(s) will execute if boolean expression is false
}
if statement in R syntax

For example,

x <- 31
if ( x %% 2 == 0 ){
   print("X is even")
}else{
  print("X is odd")
}
if Statement in R

if-else-if Statement

An if statement can be followed by an optional else-if-else statement, which is very useful for testing various conditions using a single if-else-if statement. The basic syntax for creating an if-else-if is

if ( boolean expression-1 ){
      # statements execute when the boolean expression-1 is true
} else if ( boolean expression-2 ) {
     # statements execute when the boolean expression-2 is true
} else if ( boolean expression-3 ){
    # statements execute when the boolean expression-3 is true
} else {
    # statements execute when none of the above condition is true
}

For example,

# Consider durbin watson statistics
d = -2
if (d == 2){
   print("no autocorrelation")
} else if (d > 0 &amp; d &lt; 2){
   print("Positive autocorrelation")
} else if (d > 2){
   print("successive error terms are negatively correlated")
} else {
  print("d is less than 0")
}

The value of $d (d=-2)$ will be compared with the expression’s result in the parenthesis of if or else if statement. From all of the if or else if statements only one statement will be true. In the example, $d=-2$ does not match with any of the if (or else if statement), therefore, the last statement (that is else statement) will be executed.

for loops

Computer MCQs Online Test

SPSS Data Analysis

https://rfaqs.com R Frequently Asked Questions

Import Data Files Into R

You can read/import data files into R that are produced by different software such as MS Excel, Minitab, SPSS, SAS, and STATA.

Import Data Files into R Language

In R language different data file formats can be read or imported easily. Let us start learning about how to import Data Files into R Language such as Excel, SPSS, STATA, SAS, Minitab, etc format.

Reading Excel Files in R

The XLConnect package can be used to import data files into R produced in MS Excel. First, you have to install this package.

install.packages("XLConnect")

You can check if the package is already installed using the code:

any(grepl("XLConnect", installed.packages()))

If the package is installed, you need to activate the package in your workspace (using library( ) function) to load data from MS Excel files.

importing Data Files into R Language

Suppose, you have a data file (Hald.xlsx) stored at the path "D:\STAT\STA-654\Hald.xlsx". To read this file the readWorksheetFromFile( ) function can be used. For example,

library(XLConnect) 
data &lt;- readWorksheetFromFile("D:/stat/sta-654/Hald.xlsx", sheet=1)

Since an Excel workbook can contain more than one sheet, therefore, you need to specify the sheet argument and specify which sheet you want to load into R. In this example, data from sheet 1 will be loaded.

If you want to load the whole workbook (all sheets) use the loadWorkbook( ) function to load the required worksheet as a data file frame. For example,

wb <- loadWorkbook("D:/stat/sta-654/Hald.xlsx") 
df <- readWorksheet(wb, sheet = 1)

The readxl package can also be used to read MS Excel files more easily.

library(readxl) 
df <- read_excel("Data file with path")

Note that the MS Excel files with extension: *.xls, or *.xlsx can be specified. The sheet argument can also be added, just like with the XLSconnect package.

Read SPSS Data Files

To read the SPSS files install foreign package. After loading the foreign package, the read.spss( ) function can be used to load an SPSS data file in R. For example,

library(foreign) 
mydata &lt;- read.spss ("SPSS data file with path", to.data.frame = TRUE)

The argument to.data.frame is set to TRUE so that the data is displayed in a data frame format. Since the SPSS data file contains value labels, and if you do not want the variables with value labels to be converted into R factors with corresponding levels, setuse.value.labels = FALSE. For example,

library(foreign) 

mydata <- read.spss("SPSS data file with path", 
                    to.data.frame = TRUE, 
                    use.value.labels = FALSE)

Reading STATA Data Files

To import Stata files the read.dta( ) function from the foreign package can be used. For example,

library(foreign) 
mydata &lt;- read.dta("STATA file with path")

Reading SAS Data Files

The read.sas7bdat( ) function from sas7bdat package can be used to read SAS data files into R.

library(sas7bdat) 
mydata &lt;- read.sas7bdat("SAS data file with path")

Reading Minitab Data File

Minitab data files can be imported in R using read.mtp( ) function from foreign package.

library(foreign) 
mydata &lt;- read.mtp("Minitab data file with path")

Reading RDA or RData Files

The R data files RDA and RData files can be easily read using load( ) function.

load("filename.RDA")

https://itfeature.com

https://gmstat.com

Reading Text Files In R Language: A Quick Guide

We can import data that is already saved (available) in a file created in text (*.txt) files, MS Excel, SPSS, or some other software. Before importing/reading data stored in a file (that is, reading text files in R), one should be clear and understand the following:

  1. Usually, data from spreadsheets reserved the first row as header (name of variables), while the first column was used to identify the sampling unit (observation number).
  2. Avoid names, and the value of fields with blank spaces, each word may be interpreted as a separate variable, resulting in errors.
  3. To concatenate words, use a full stop (.) instead of space between words.
  4. Name variables with short or abbreviated names.
  5. Try to avoid using names of variables that contain symbols such as ?, $, %, ^, *, (, ), -, #, <, >, /, |, ,\, [, ], {, and }.
  6. Delete comments you have made in your Excel file.
  7. Make sure missing values in your dataset are indicated with NA.

Preparing R workspace

Before importing data in R, it is better to delete all objects using the following line of code

rm(list = ls() )

The rm( ) function “remove objects from a specified environment”. Since no argument to ls( ) function is provided, datasets and user-defined functions will be deleted.

Confirm your working directory before importing a file to R, using

getwd()

If possible change the path of your working directory. such as

setwd("D:\\Stat\\STA-654")

Note you may have to create the directory (folder) and the path discussed above.

Reading Text Files in R

Reading Text Files In R Language

Reading Text files in R is easy and simple enough. If you have data in a *.txt file or a tab-delimited text file, you can easily import it with the read.table( ) function. Suppose we have a data file named "Hald.txt" stored at the path "D:\STAT\STA-654\Hald.txt". The following code line can be used for reading text files in R:

datafile <- read.table ("D:/stat/sta-654/Hald.txt", header = TRUE)

If you have data stored on some web address, you can also import it as

datafile <- read.table ("http://itfeature.com/wp-content/uploads/2020/03/Hald.txt", header = TRUE)

Note that the first argument of read.table() provide the name and extension of the file that you want to import in R. The header argument specifies whether or not you have specified column names in your data file. The Hald.txt file will be imported as data.frame an object.

Computer MCQs Online Test

MCQs in Statistics