2018-09-09/ R Basics

Arithmetic

Comment:#

Addition: +

Subtraction: -

Multiplication: *

Division: /

Exponentiation: ^

Modulo: %%

Assign:<-

Basic data types in R

CASE SENSITIVE

Decimal values like 4.5 are called numerics.

Natural numbers like 4 are called integers. Integers are also numerics.

Boolean values (TRUE or FALSE) are called logical.

Text (or string) values are called characters.

Check the class of variables: class()

Vector

Vectors are one-dimension arrays that can hold numeric data, character data, or logical data. In other words, a vector is a simple tool to store data.

Is() check the variables in the workspace.


numeric_vector <- c(1, 2, 3)

character_vector <- c("a", "b", "c")

You can give a name to the elements of a vector with the names() function. Have a look at this example:


some_vector <- c("John Doe", "poker player")

names(some_vector) <- c("Name", "Profession")


c(1, 2, 3) + c(4, 5, 6)

c(1 + 4, 2 + 5, 3 + 6)

c(5, 7, 9)

Index: the first element in a vector has index 1, not 0

poker_vector[2:4] == poker_vector[c(2, 3, 4)]

note: 2-4, including 4th

You can also use the element names to select multiple elements, for example: poker_vector[c("Monday", "Tuesday")]

The (logical) comparison operators

< for less than

> for greater than

<= for less than or equal to

>= for greater than or equal to

== for equal to each other

!= not equal to each other

You can select the desired elements, by putting selection_vector between the square brackets that follow poker_vector:

poker_vector[selection_vector]

R knows what to do when you pass a logical vector in square brackets: it will only select the elements that correspond to TRUE in selection_vector

matrix


matrix(1:9, byrow = TRUE, nrow = 3)

The argument byrow indicates that the matrix is filled by the rows. If we want the matrix to be filled by the columns, we just place byrow = FALSE.

The third argument nrow indicates that the matrix should have three rows.

Similar to vectors, you can add names for the rows and the columns of a matrix:

rownames(my_matrix) <- row_names_vector

colnames(my_matrix) <- col_names_vector

In R, the function rowSums() conveniently calculates the totals for each row of a matrix. This function creates a new vector:

rowSums(my_matrix)

You can add a column or multiple columns to a matrix with the cbind() function, which merges matrices and/or vectors together by column. For example:

adding colums:big_matrix <- cbind(matrix1, matrix2, vector1 ...)

rbind(): paste matrixs together

my_matrix[1,2] selects the element at the first row and second column.

my_matrix[1:3,2:4] results in a matrix with the data on the rows 1, 2, 3 and columns 2, 3, 4.

my_matrix[,1] selects all elements of the first column.

my_matrix[1,] selects all elements of the first row.

my_matrix1 * my_matrix2 creates a matrix where each element is the product of the corresponding elements in my_matrix1 and my_matrix2

Those who are familiar with matrices should note that this is not the standard matrix multiplication for which you should use %*% in R.

Factors

sex_vector <- c("Male","Female","Female","Male","Male")

It is clear that there are two categories, or in R-terms 'factor levels', at work here: "Male" and "Female".

The function factor() will encode the vector as a factor:

factor_sex_vector <- factor(sex_vector)

There are two types of categorical variables: a nominal categorical variable and an ordinal categorical variable.

A nominal variable is a categorical variable without an implied order. This means that it is impossible to say that 'one is worth more than the other'. For example, think of the categorical variable animals_vector with the categories "Elephant", "Giraffe", "Donkey" and "Horse". Here, it is impossible to say that one stands above or below the other. (Note that some of you might disagree ;-) ).

In contrast, ordinal variables do have a natural ordering. Consider for example the categorical variable temperature_vector with the categories: "Low", "Medium" and "High". Here it is obvious that "Medium" stands above "Low", and "High" stands above "Medium".

Change the name of the factors level: levels(factor_vector) <- c("name1", "name2",...)

Watch out the order with which you assign the levels is important. If you type levels(factor_survey_vector), you'll see that it outputs [1] "F" "M". If you don't specify the levels of the factor when creating the vector, R will automatically assign them alphabetically. To correctly map "F" to "Female" and "M" to "Male", the levels should be set to c("Female", "Male"), in this order.

This will give you a quick overview of the contents of a variable: summary(my_var)

Data Frame

When you work with (extremely) large data sets and data frames, your first task as a data analyst is to develop a clear understanding of its structure and main elements. Therefore, it is often useful to show only a small part of the entire data set.
the function head() enables you to show the first observations of a data frame. Similarly, the function tail() prints out the last observations in your data set.

Both head() and tail() print a top line called the 'header', which contains the names of the different variables in your data set.

Have a look at the structure

Another method that is often used to get a rapid overview of your data is the function str(). The function str() shows you the structure of your data set. For a data frame it tells you:

  • The total number of observations (e.g. 32 car types)
  • The total number of variables (e.g. 11 car features)
  • A full list of the variables names (e.g. mpg, cyl ... )
  • The data type of each variable (e.g. num)
  • The first observations

Applying the str() function will often be the first thing that you do when receiving a new data set or data frame. It is a great way to get more insight in your data set before diving into the real analysis.

Create a data frame

You construct a data frame with the data.frame() function. As arguments, you pass the vectors from before: they will become the different columns of your data frame. Because every column has the same length, the vectors you pass should also have the same length. But don't forget that it is possible (and likely) that they contain different types of data.

# Definition of vectors
name <- c("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
type <- c("Terrestrial planet", "Terrestrial planet", "Terrestrial planet", 
          "Terrestrial planet", "Gas giant", "Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532, 11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03, 0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)

# Create a data frame from the vectors
planets_df <- data.frame(name,type,diameter,rotation,rings)

# Check the structure of planets_df
str(planets_df)

Selection elements:

  • Similar to vectors and matrices, you select elements from a data frame with the help of square brackets [ ]. By using a comma, you can indicate what to select from the rows and the columns respectively. For example:
    my_df[1,2] selects the value at the first row and second column in my_df.
    my_df[1:3,2:4]selects rows 1, 2, 3 and columns 2, 3, 4 in my_df.
    Sometimes you want to select all elements of a row or column. For example, my_df[1, ]selects all elements of the first row.
  • Use the variable names to select columns of a data frame. Suppose you want to select the first three elements of the type column. One way to do this is planets_df[1:3,2]. It is often easier to just make use of the variable name: planets_df[1:3,"type"].
  • Select an entire column. Use $, like planets_df$diameter.
  • Select subset: subset(my_df, subset = some_condition)

Sorting

order() is a function that gives you the ranked position of each element when it is applied on a variable, such as a vector for example:

> a <- c(100, 10, 1000)
> order(a)
[1] 2 1 3

10, which is the second element in a, is the smallest element, so 2 comes first in the output of order(a). 100, which is the first element in a is the second smallest element, so 1 comes second in the output of order(a).

This means we can use the output of order(a) to reshuffle a:

> a[order(a)]
[1]   10  100 1000

e.g.
Instruction:
Call order() on planets_df$diameter (the diameter column of planets_df). Store the result as positions.
Now reshuffle planets_df with the positions vector as row indexes inside square brackets. Keep all columns. Simply print out the result.

# Use order() to create positions
positions <-  order(planets_df$diameter)

# Use positions to sort planets_df
planets_df[positions,]

你可能感兴趣的:(2018-09-09/ R Basics)