<jupyter_start><jupyter_text>R Notes----1) R Basics    1.1) Arithmetics: +,-, *,^, %%    1.2) Data types    1.3) Vectors: names(), sum(), selection vector    1.4) Matrices: matrix(), colnames(), rownames(), dimnames(), cbind(), rbind(), matrix arithmetics    1.5) Factors: factor(), levels(), summary(), selection, comparison    1.6) DataFrames: head(), tail(), str(), summary(), data.frame(), selection, subset(), order(),     1.7) Lists: create list, slice list, concat list2) R Intermediate    2.1) Relational Operators: ==, !=, >, <          1) R Basics  1.1) ArithmeticsFor simple arithmetics use:+ , - , * , / , Exponetiation : ^Module : %%For matrix arithmetics use %*% or %/ % , else all elements are calculated and the arithmetic is not the usual matrix one.--- 1.2) Basic Data TypesNumerics   : 4.5Integers   : 4Boolean    : TRUE, FALSE, T, FCharacters : 'this is a text', 'abc'Vectors, Matrices, Factors and Lists are made using the basic data types.To find the type of a variable use: **class(variable_name)**<jupyter_code>var <- 4.1
class(var)<jupyter_output><empty_output><jupyter_text>---  1.3) VectorsTo create a vector<jupyter_code>myvec <- c(1,3,5.5); myvec<jupyter_output><empty_output><jupyter_text>Naming the vector by :<jupyter_code>names(myvec) <- c('a','b','c'); myvec<jupyter_output><empty_output><jupyter_text>Summing the elements of a vector:<jupyter_code>sum(myvec)<jupyter_output><empty_output><jupyter_text>Select a vector index:<jupyter_code>myvec[2]        # counting starts from 1 not 0!
myvec[c(1,2)]   # multiple select
myvec[1:2]      # slicing
myvec[c('a','b')] # by name<jupyter_output><empty_output><jupyter_text>---Selection by vector comparison:<jupyter_code>poker_vector <- c(140, -50, 20, -120, 240);
selection <- poker_vector > 0;
selection
winnings_vector <- poker_vector[selection]; winnings_vector<jupyter_output><empty_output><jupyter_text>--- 1.4) MatricesUsing the matrix function we can make a 2D matrix:<jupyter_code>matrix(1:9, byrow = TRUE, nrow =3) # byrow : fill by rows , nrow = # rows<jupyter_output><empty_output><jupyter_text>---**create a matrix using vectors:**<jupyter_code>new_hope <- c(460.998, 314.4);
empire_strikes <- c(290.475, 247.900);
return_jedi <- c(309.306, 165.8);

star_wars_matrix = matrix(c(new_hope,empire_strikes,return_jedi), nrow=3,
                          byrow=TRUE);
star_wars_matrix<jupyter_output><empty_output><jupyter_text>---**Name your columns, rows**<jupyter_code>colnames(star_wars_matrix) <- c("US", "non-US");
rownames(star_wars_matrix) <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi");
star_wars_matrix<jupyter_output><empty_output><jupyter_text>----**Summing rows and cols:**<jupyter_code>colSums(star_wars_matrix)
rowSums(star_wars_matrix)
box_office_all <- c(461, 314.4, 290.5, 247.9, 309.3, 165.8);
movie_names <- c("A New Hope","The Empire Strikes Back","Return of the Jedi");
col_titles <- c("US","non-US")

#### NAME USING VECTOR NAMES
star_wars_matrix <- matrix(box_office_all, nrow = 3, byrow = TRUE, 
                           dimnames = list(movie_names, col_titles));

star_wars_matrix<jupyter_output><empty_output><jupyter_text>---**Adding columns and rows** : cbind(), rbind()<jupyter_code>worldwide_vector <- rowSums(star_wars_matrix);
all_wars_matrix <- cbind(star_wars_matrix, worldwide_vector)
all_wars_matrix
box_office_2 <- c(474, 552, 310, 338, 380, 468);
movie_names_2 <- c("The Phantom Menace","Attack of the Clones","Revenge of the Sith");
col_titles_2 <- c("US","non-US")
star_wars_matrix_2 <- matrix(box_office_2, nrow = 3, byrow = TRUE, 
                           dimnames = list(movie_names_2, col_titles_2));


star_wars_all <- rbind(star_wars_matrix,star_wars_matrix_2);
star_wars_all<jupyter_output><empty_output><jupyter_text>----** Selecting elements of matrix **<jupyter_code>star_wars_all[1,2] #1st row, 2nd column
star_wars_all[ ,2] # ALL rows from 2nd column
star_wars_all[1, ] # 1st row, all columns
star_wars_all[1:2,] #slicing
mean(star_wars_all[1:2,])<jupyter_output><empty_output><jupyter_text>---**Arithmetics with matrices**<jupyter_code>star_wars_all *2 # multiply all elements by 2<jupyter_output><empty_output><jupyter_text>--- 1.4 FactorsFactors are used for categorical variables, i.e. 'Gender'Having a vector with elements from two categories you can make a factor variable by calling the `factor()` function:<jupyter_code>gender_vector <- c("Male", "Female", "Female", "Male", "Male");
factor_gender_vector <- factor(gender_vector);
factor_gender_vector<jupyter_output><empty_output><jupyter_text>---There are two types of categorical variables **nominal** and **ordinal**.You can use arguments in the factor function to define the levels of an ordinal variable.For example:<jupyter_code>animals_vector <- c("Elephant", "Giraffe", "Donkey", "Horse")
temperature_vector <- c("High", "Low", "High","Low", "Medium")

factor_animals_vector <- factor(animals_vector)
factor_animals_vector
factor_temperature_vector <- factor(temperature_vector, order = TRUE, levels = c("Low", "Medium", "High"))
factor_temperature_vector 

# in R terminal this shows also the levels :
# for the nominal it states: Levels: Donkey Elephant Giraffe Horse
# while for the ordinal : Levels: Low < Medium < High<jupyter_output><empty_output><jupyter_text>---**You can change the names of the levels by `levels()` function:**<jupyter_code>survey_vector <- c("M", "F", "F", "M", "M")
factor_survey_vector <- factor(survey_vector)
factor_survey_vector<jupyter_output><empty_output><jupyter_text>but I want 'Male' and 'Female' !<jupyter_code>levels(factor_survey_vector) <- c('Female', 'Male')
factor_survey_vector<jupyter_output><empty_output><jupyter_text>---**Summary** of factors<jupyter_code>summary(survey_vector)
summary(factor_survey_vector)<jupyter_output><empty_output><jupyter_text>---** Selection **<jupyter_code>factor_survey_vector[1]
factor_survey_vector[2]<jupyter_output><empty_output><jupyter_text>---** Comparison of factors **Comparison does not work for nominal factors,but works fine for ordinal!!<jupyter_code>factor_survey_vector[1]>factor_survey_vector[2] ## NA! Doesn't work for 
                                                ## nominal factors!
speed_vector <- c("Fast", "Slow", "Slow", "Fast", "Ultra-fast")
factor_speed_vector <- factor(speed_vector, ordered = TRUE, 
                              levels = c("Slow", "Fast", "Ultra-fast"))

compare_them <- factor_speed_vector[2]>factor_speed_vector[5]

# Is data analyst 2 faster than data analyst 5?
compare_them<jupyter_output><empty_output><jupyter_text>---- 1.6) DataFrameContrary to matrices, dataframes can hold data of various types<jupyter_code>mtcars;  # dataframe included in R<jupyter_output><empty_output><jupyter_text>---**Quick look at dataframe**head(), tail(), str() [structure]<jupyter_code>head(mtcars,2)
tail(mtcars,4)
str(mtcars) # means structure
summary(mtcars)  # returns summary statistics<jupyter_output><empty_output><jupyter_text>---** Creating a data.frame()**You can create a dataframe using simple vectors by calling the `data.frame()` function<jupyter_code>planets <- 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 the data frame:
planets_df  <- data.frame(planets, type, diameter, rotation, rings)
planets_df  # indexes the rows and names the columns by the name of vector<jupyter_output><empty_output><jupyter_text>---**Slicing a data frame**As with matrices you can use [1,2], [1, ], [1:3, ] etc** OR USE THE NAME OF THE COLUMN!!! **<jupyter_code>planets_df[1:3,1]
planets_df[3:8, "diameter"]
planets_df$diameter # this returns a vector with the elements of the column
## similar to planets_df[ ,"diameter"]<jupyter_output><empty_output><jupyter_text>---**Selection of df entries using selector vector**<jupyter_code>selection_rings <- planets_df$rings
planets_with_rings <- planets_df[selection_rings, ] # all columns, 
                                                    #rows with True
planets_with_rings<jupyter_output><empty_output><jupyter_text>** Subset()**Use the subset function to select entries from a df<jupyter_code>planets_with_rings_2 <- subset(planets_df, subset = rings == TRUE);
planets_with_rings_2<jupyter_output><empty_output><jupyter_text>----** Order ** the order() function returns the hierarchical order in a vector:<jupyter_code>a<- c(100, 150, 101)
order(a)<jupyter_output><empty_output><jupyter_text>This can be used in data frames. For example order the planet df with the largest planet in the top.To do this use the order function with the decreasing = TRUE argument to make a vector and then pass it in the df :<jupyter_code>positions <- order(planets_df$diameter, decreasing=TRUE)
largest_first_df <- planets_df[positions, ]
largest_first_df<jupyter_output><empty_output><jupyter_text>--- 1.7) ListsLists hold together objects from different data types, sizes and flavors under one common name.To make a list just use the `list()` function with arguments the things you want the list to hold<jupyter_code>vec <- 1:10;
mat <- matrix(1:9, byrow=TRUE, ncol=3)
mdf <- mtcars[1:10,]
my_list <- list(vec, mat, mdf)
my_list<jupyter_output><empty_output><jupyter_text>Update the `names(my_list)` to name the object your list holds:<jupyter_code>names(my_list) <- c("vector", "matrix", "dataframe")
my_list<jupyter_output><empty_output><jupyter_text>---** Select elements from list **To select from the list use the double bracket [[ ]]<jupyter_code>my_list[[1]] # returns the object 1 (ie the vector)
my_list[[2]]
my_list[[1]][2] #from the list the 1st object (vec), 
                # from that the 2nd element<jupyter_output><empty_output><jupyter_text>----**Append to list** To append an info in the list use the c() function.To also name the new item when concatinating use the syntax :` c(list, name=new_var)`<jupyter_code>year <- 1980
my_list_2 <- c(my_list, myyear=year)
my_list_2<jupyter_output><empty_output><jupyter_text>------ 2) Intermediate R 2.1) Relational OperatorsThese operators are ==, !=, ,  and can be used to return TRUE or FALSE.Some interesting cases:<jupyter_code>3>5
FALSE == TRUE
FALSE < TRUE  # TRUE = 1, FALSE = 0
"Hello" > "Goodbye" # alphabetical order (G < H < I ...)<jupyter_output><empty_output><jupyter_text>---For vectors:<jupyter_code>linkedin <- c (10,20,30,40,60)
linkedin > 30
facebook <- c(10,50,20,56) # check the warning
linkedin<facebook<jupyter_output>Warning message:
In linkedin < facebook: longer object length is not a multiple of shorter object length
{'fraction_non_alphanumeric': 0.14013793103448277, 'fraction_numerical': 0.027586206896551724, 'mean_word_length': 5.647921760391198, 'pattern_counts': {'":': 0, '<': 199, '<?xml version=': 0, '>': 143, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '34', 'dir': 'jupyter-structured-clean-dedup', 'id': '386267', 'license': 'MIT', 'n_tokens_mistral': 4084, 'n_tokens_neox': 3720, 'n_words': 955, 'path': 'R_Notes.ipynb', 'repo_name': 'nkarast/notebooks', 'size': '10875'}