<- 1:10
x <- 5.8
y <- 1+5i z
Operations with R
Let’s define some values named ‘x’, ‘y’, and ‘z’.
What type of value is x? (use “class” function). What about y and z?
class(x)
[1] "integer"
What is the product of x times y?
*y x
[1] 5.8 11.6 17.4 23.2 29.0 34.8 40.6 46.4 52.2 58.0
The function “c” combine values into a vector or list. Characters needs to be between ““. The semicolon or a new line separates processes.
What are the differences between the three x values created below? what is the final value for x?
<- c(TRUE, TRUE, FALSE); x x
[1] TRUE TRUE FALSE
<-c("yes", "yes", "no", "yes"); x x
[1] "yes" "yes" "no" "yes"
<- as.factor(c("yes", "yes", "no", "yes")); x x
[1] yes yes no yes
Levels: no yes
How many “yes” or “no” the value x has?
table(x)
x
no yes
1 3
Can I transform these character values to numbers?
unclass(x)
[1] 2 2 1 2
attr(,"levels")
[1] "no" "yes"
What these functions do?
rep(10,4); seq(1,5,by=0.1)
[1] 10 10 10 10
[1] 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8
[20] 2.9 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4.0 4.1 4.2 4.3 4.4 4.5 4.6 4.7
[39] 4.8 4.9 5.0
Let’s create a matrix
<- matrix(1:6, nrow = 2, ncol = 3) m
How many rows and columns the matrix named ‘m’ has?
dim(m)
[1] 2 3
Let’s create a data frame
<- data.frame(num = 1:4, boo = c(T, T, F,F), chr = c("yes","no","perhaps","whynot")); df
Look at the differences in the matrix and data.frame functions. In the matrix, ‘nrow’and ’ncol’ are arguments for the function. In the data frame, ‘num’, ‘boo’, and ‘chr’ are column names.
What are the dimensions of the data frame?
dim(df)
[1] 4 3
How are are the columns named?
colnames(df)
[1] "num" "boo" "chr"
Can I rename those columns as ‘meh’, ‘mih’, and ‘moh’, for example?
colnames(df)<-c("meh","mih","moh")
I want to look at the values contained in the column named “moh” (the third column). How can I do that?
$moh; df[[3]]; df[,3] ; df[,-(1:2)]; df[["moh"]] df
[1] "yes" "no" "perhaps" "whynot"
[1] "yes" "no" "perhaps" "whynot"
[1] "yes" "no" "perhaps" "whynot"
[1] "yes" "no" "perhaps" "whynot"
[1] "yes" "no" "perhaps" "whynot"
I want to look at the value contained in the first row and the third column. How can I do that?
1,3] df[
[1] "yes"
How can I assign the values contained in the third column to a new value?
<- df[["moh"]] new_val
What type of value is this?
class(new_val)
[1] "character"
How can I create a new data frame with the values contained in the second and third column?
<- df[2:3] new_df
Are you sure it is a data frame?
class(new_df)
[1] "data.frame"
What about with the values contained in the first and third column?
<- df[c(1,3)] new_df2
Can you think on another way to get this new_df2?