### Overview of Lesson

In this lesson, we’ll work with logicals and factors.

### Logical values

There are two logical values: TRUE and FALSE We use logical values in many ways, but most typically in one of two:

Logical Use Description Example
Conditions We assess whether a condition has been satisfied or not. Is 2 greater than 1?
Paramters We want a parameter in a function or command to be switched on or off . Should the function read in the data by row?

#### Logical Conditions

In this lesson, we focus only on the first: logical conditionals. To assess logical conditions we use relational operators. Below I show the use of all relational operators, with R returning whether or not they are true or false.

1==1 # Is 1 equal to 1? (TRUE)

1!=1 # Is 1 different (not equal) to 1? (FALSE)

1>2 # Is 1 greater than 2? (FALSE)

1<2 # Is 1 less than 2? (TRUE)

1>=1 #is 1 greater than or equal to 1? (TRUE)

1<=2 #is 1 less than or equal to 2? (TRUE)

As always, we can provide R with any object and it will be happy to evalute it relative to another object.

#### Logical Subsetting

An important skill to have is to be able to subset data on the basis of logicals. Say we have a vector we call a.

a<-c(seq(from=-2, to=2)) #creating a sequence from -2 to 2 in vector a

#We can then check which values are below 0.
a<0 #what values in a are less than 0?
#Which returns a vector of logicals.

This is more useful when subsetting.

b<-a[a<0] #Here we are saying that b gets those entires in a for which a is less than O is TRUE.
b

### Factors

Categorical variables can be represented as factors. This is common in statistical programming. For instance, say we have a list of genders.

gender<-c("male","male","female","female","male","female","female") # I create the vector gender
gender.factor<-factor(gender)  #I use the factor function to turn into a factor
gender.factor #I see information about this new vector, including the levels, or the type of values that the vector info takes. 

We can use the information contained in these factors to subset the vector.

gender[gender=="male"]# the new vector gender, is a subset of the original gender with values that are male

This returns only the male entries. The usefulness of this step will become obvious. But for now, notice that this operation might be useful to subset larger datasets. For instance, to subset all information relevant only to female entries for further analysis.

In the next lesson we will discuss elementary functions.