SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Downloaden Sie, um offline zu lesen
R for You
Andreas Chandra
linkedin.com/in/chandraandreas
Contents
- Basic R
- Data Structures
- Reading Data
- Charts
- Function
- Conditional Statements
- Iteration
- Grouping
- Reshape
- String Operations
BasicR
Basic R
- Math Operation
- Variable
- Data type
- Vectors
- Calling Function
- Missing Data
Basic R - Math
Basic Operation:
2 + 2
2 - 1
5 / 2
10 * 2
10 % 2
2 + (5 - 3)
Variable
X <- 10
X
10 <- Z
Z
A <- B <- 10
A
B
assign(“i”, 99)
# Untuk menghapus variabel
rm(B)
Data Types
● Numeric
● Chars
● Dates
● Boolean
Vectors
X <- c(1,2,3,4,5)
Operations
X * 3
X + 2
Factor
X <- c(“Januari”, “Februari”, “Maret”, “April”, “Januari”)
X_factor <- as.factor(X)
>X_factor
[1] Januari Februari Maret April Januari
Levels: April Februari Januari Maret
Calling Function
function(<var>)
Ex:
mean(var_name)
sd(var_name)
sqrt(varn_name)
Data Structures
Data Frames
# create
df <- data.frame()
Function in df:
nrow tail
ncol class
dim df[row, col]
rownames df[, c(“pertama”, “kedua”)]
head Df[2:3, ]
Lists
X <- list(1:3,4:6,7:9)
names(X)
None
> names(X) <- c("pertama", "kedua", "ketiga")
> X
$pertama
[1] 1 2 3
$kedua
[1] 4 5 6
$ketiga
[1] 7 8 9
Matrices
> X <- matrix(1:10, nrow = 5)
> Y <- matrix(11:20, nrow = 5)
>
> X
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
> Y
[,1] [,2]
[1,] 11 16
[2,] 12 17
[3,] 13 18
[4,] 14 19
[5,] 15 20
>
> Z <- X * Y
> Z
[,1] [,2]
[1,] 11 96
[2,] 24 119
[3,] 39 144
[4,] 56 171
[5,] 75 200
Arrays
> arr <- array(1:12, dim = c(2, 3, 2))
> arr
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
Reading Data
read.table
> read.table(file, header = TRUE, sep = ",")
#full detail
> read.table(file, header = FALSE, sep = "", quote = ""'",
+ dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"),
+ row.names, col.names, as.is = !stringsAsFactors,
+ na.strings = "NA", colClasses = NA, nrows = -1,
+ skip = 0, check.names = TRUE, fill = !blank.lines.skip,
+ strip.white = FALSE, blank.lines.skip = TRUE,
+ comment.char = "#",
+ allowEscapes = FALSE, flush = FALSE,
+ stringsAsFactors = default.stringsAsFactors(),
+ fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)
read.csv
> read.csv(file, header = TRUE, sep = ",", quote = """,
+ dec = ".", fill = TRUE, comment.char = "")
Excel (xlsx)
read.xlsx(file, sheetIndex, sheetName=NULL, rowIndex=NULL,
startRow=NULL, endRow=NULL, colIndex=NULL,
as.data.frame=TRUE, header=TRUE, colClasses=NA,
keepFormulas=FALSE, encoding="unknown")
Database (RODBC)
odbcConnect()
Charts
Histogram
Scatterplot
> library(ggplot2)
> library(gapminder)
>
> data(gapminder)
>
> #create plot
> plot(lifeExp ~ gdpPercap, data =
gapminder)
> #change scientific notation
> options(scipen = 999)
Boxplots
boxplot(gapminder$gdpPercap)
ggplot
ggplot(gapminder,
aes(x = lifeExp, y =
gdpPercap)) +
geom_point(aes(color =
factor(continent)))
Function
Basic Function
> hello_fun <- function(){
+ print("hello world")
+ }
>
> hello_fun()
[1] "hello world"
Function with args
> hello_fun <- function(name){
+ print(sprintf("hello world %s", name))
+ }
> hello_fun(name = "Jakarta")
[1] "hello world Jakarta"
Default args
> hello_fun <- function(name = "Bali"){
+ print(sprintf("hello world %s", name))
+ }
> hello_fun()
[1] "hello world Bali"
> hello_fun(name = "Bandung")
[1] "hello world Bandung"
Return Values
> hello_fun <- function(name = "Bali"){
+ return(sprintf("hello world %s", name))
+ }
> greetings <- hello_fun(name = "Bandung")
> greetings
[1] "hello world Bandung"
Conditional
IF ElSE
> grade_checker <- function(grade){
+ if(grade > 7){
+ return("Good")
+ }else if(grade > 4){
+ return("Enough")
+ }else{
+ return("Bad")
+ }
+ }
> grade_checker(9)
[1] "Good"
Switch
> class_switch <- function(class){
+ switch(class,
+ "H" = "High",
+ "M" = "Medium",
+ "L" = "Low",
+ NA)
+ }
> class_switch("H")
[1] "High"
Iter-ate
For
> names <- c("Ada", "Abu", "Abi", "Abe", "Abo")
> for(name in names){
+ print(name)
+ }
[1] "Ada"
[1] "Abu"
[1] "Abi"
[1] "Abe"
[1] "Abo"
While
> names <- c("Ada", "Abu", "Abi", "Abe", "Abo")
> index <- 1
> while (index <= length(names)){
+ print(names[index])
+ index = index + 1
+ }
[1] "Ada"
[1] "Abu"
[1] "Abi"
[1] "Abe"
[1] "Abo"
Grouping
apply
> a_matrix <- matrix(1:9, nrow = 3)
> a_matrix
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
>
> apply(a_matrix, 1, sum)
[1] 12 15 18
sapply, lapply
> a_list <- list(A = matrix(1:9, 3), B = 1:9, C = matrix(1:6, 3))
> lapply(a_list, mean)
$A
[1] 5
$B
[1] 5
$C
[1] 3.5
> sapply(a_list, mean)
A B C
5.0 5.0 3.5
aggregate
> data(diamonds)
> head(diamonds)
# A tibble: 6 x 10
carat cut color clarity depth table price x y z
<dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1 0.230 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43
2 0.210 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
3 0.230 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
4 0.290 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63
5 0.310 Good J SI2 63.3 58.0 335 4.34 4.35 2.75
6 0.240 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48
>
> aggregate(price ~ cut + color, diamonds, mean)
cut color price
1 Fair D 4291.061
2 Good D 3405.382
3 Very Good D 3470.467
4 Premium D 3631.293
5 Ideal D 2629.095
6 Fair E 3682.312
7 Good E 3423.644
data.table
> require(data.table)
> head(diamonds)
# A tibble: 6 x 10
carat cut color clarity depth table price x y z
<dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1 0.230 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43
2 0.210 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
3 0.230 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
4 0.290 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63
5 0.310 Good J SI2 63.3 58.0 335 4.34 4.35 2.75
6 0.240 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48
> diamonds_dt <- data.table(diamonds)
> diamonds_dt[, sum(price), by = cut]
cut V1
1: Ideal 74513487
2: Premium 63221498
3: Good 19275009
4: Very Good 48107623
5: Fair 7017600
Reshaping the
Data
cbind & rbind
> sport = c("Hoot", "Base", "Foot")
> league = c("Hoot1", "Base2", "Foot3")
> trophy = c("Hoot4", "Base5", "Foot6")
>
> trop1 = cbind(sport, league, trophy)
>
> trop2 <- data.frame(sport = c("Basket", "Golf"),
+ league = c("Laptop", "Notebook"),
+ trophy = c("rank1", "rank2"))
>
> trop3 = rbind(trop1, trop2)
>
> trop3
sport league trophy
1 Hoot Hoot1 Hoot4
2 Base Base2 Base5
3 Foot Foot3 Foot6
4 Basket Laptop rank1
5 Golf Notebook rank2
merge
> customer = data.frame(id = c(1,2,3),
+ name = c("Ada", "Adi", "Ade"),
+ address = c("Jkt", "Bdg", "Jog"))
> order = data.frame(id = c(1,2,3),
+ order = c("Gayuung", "Sabun", "Pipa"))
> trans = merge(customer, order, by.customer = c("id", "id"))
> trans
id name address order
1 1 Ada Jkt Gayuung
2 2 Adi Bdg Sabun
3 3 Ade Jog Pipa
Others
Plyr - merge
Data.table - merge
Reshape2 - melt
> provinsi <- c("DKI Jakarta", "Jawa Barat", "Jawa Tengah")
> SD <- c(100,200,300)
> SMP <- c(120,210,310)
> SMA <- c(130,220,320)
> df <- data.frame(provinsi, SD, SMP, SMA)
> melt(df, id = c("provinsi"))
provinsi variable value
1 DKI Jakarta SD 100
2 Jawa Barat SD 200
3 Jawa Tengah SD 300
4 DKI Jakarta SMP 120
5 Jawa Barat SMP 210
6 Jawa Tengah SMP 310
7 DKI Jakarta SMA 130
8 Jawa Barat SMA 220
9 Jawa Tengah SMA 320
Reshape - dcast
Strings
paste
Join 2 strings
> paste("Andreas", "Chandra")
> paste("DC", "2017", "01", "31", sep = "-")
[1] "DC-2017-01-31"
[1] "Hallo Andre" "Hey Chan" "Hallo Dra"
sprintf
> Name <- "Rio"
> Age <- 20
> City <- "NYC"
>
> sprintf("I am %s, %d years old, Live in %s", Name, Age,
City)
[1] "I am Rio, 20 years old, Live in NYC"
Printf format https://en.wikipedia.org/wiki/Printf_format_string
Regular expression
> library(stringr)
> bad_john <- str_detect(string = names_list, "John")
> good_john <- str_detect(string = names_list, ignore.case("John"))
Please use (fixed|coll|regex)(x, ignore_case = TRUE) instead of
ignore.case(x)
> names_list[good_john]
[1] "John Adams" "egi john" "John Ad" "john abs"
> sum(bad_john)
[1] 2
> sum(good_john)
[1] 4
Regular expression
str_detect()
str_split()
str_trim()
str_extract()
Jared P. Lander, 2014, R for Everyone

Weitere ähnliche Inhalte

Was ist angesagt?

Sql
SqlSql
SqlJoao
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In RRsquared Academy
 
Getting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commitsGetting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commitsBarbara Fusinska
 
СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3Technopark
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 
Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...Dr. Volkan OBAN
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
 
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜Takashi Kitano
 
D3 svg & angular
D3 svg & angularD3 svg & angular
D3 svg & angular500Tech
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection apitrygvea
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data ManipulationChu An
 
Visualizing Postgres
Visualizing PostgresVisualizing Postgres
Visualizing Postgreselliando dias
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheetGil Cohen
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapHoward Lewis Ship
 
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180Mahmoud Samir Fayed
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tddMarcos Iglesias
 
2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규
2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규
2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규민규 조
 

Was ist angesagt? (20)

Groovy kind of test
Groovy kind of testGroovy kind of test
Groovy kind of test
 
Sql
SqlSql
Sql
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In R
 
Getting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commitsGetting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commits
 
СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
Sql
SqlSql
Sql
 
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
 
D3 svg & angular
D3 svg & angularD3 svg & angular
D3 svg & angular
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection api
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
Visualizing Postgres
Visualizing PostgresVisualizing Postgres
Visualizing Postgres
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 
Sql
SqlSql
Sql
 
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tdd
 
2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규
2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규
2018. 03 파이썬 격월 세미나 - 고딩 파이썬 개발자 백엔드 엔지니어 인턴 분투기 : 조민규
 

Ähnlich wie R for you

An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSigmoid
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수용 최
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
Advanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIAdvanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIDr. Volkan OBAN
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Chapter 3 Built-in Data Structures, Functions, and Files .pptx
Chapter 3 Built-in Data Structures, Functions, and Files .pptxChapter 3 Built-in Data Structures, Functions, and Files .pptx
Chapter 3 Built-in Data Structures, Functions, and Files .pptxSovannDoeur
 

Ähnlich wie R for you (20)

R programming language
R programming languageR programming language
R programming language
 
R
RR
R
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Py3k
Py3kPy3k
Py3k
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. Jyotiska
 
CLUSTERGRAM
CLUSTERGRAMCLUSTERGRAM
CLUSTERGRAM
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
R programming
R programmingR programming
R programming
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
A Shiny Example-- R
A Shiny Example-- RA Shiny Example-- R
A Shiny Example-- R
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
 
Advanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIAdvanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part II
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Chapter 3 Built-in Data Structures, Functions, and Files .pptx
Chapter 3 Built-in Data Structures, Functions, and Files .pptxChapter 3 Built-in Data Structures, Functions, and Files .pptx
Chapter 3 Built-in Data Structures, Functions, and Files .pptx
 

Mehr von Andreas Chandra

Resume Andreas Chandra_online.pdf
Resume Andreas Chandra_online.pdfResume Andreas Chandra_online.pdf
Resume Andreas Chandra_online.pdfAndreas Chandra
 
Intro to machine learning
Intro to machine learningIntro to machine learning
Intro to machine learningAndreas Chandra
 
Social Network Analysis dengan NetworkX
Social Network Analysis dengan NetworkXSocial Network Analysis dengan NetworkX
Social Network Analysis dengan NetworkXAndreas Chandra
 
Tutorial penggunaan big query
Tutorial penggunaan big queryTutorial penggunaan big query
Tutorial penggunaan big queryAndreas Chandra
 
Penerapan text mining menggunakan python
Penerapan text mining menggunakan pythonPenerapan text mining menggunakan python
Penerapan text mining menggunakan pythonAndreas Chandra
 
Perancangan aplikasi data mining berbasis web dengan algoritma
Perancangan aplikasi data mining berbasis web dengan algoritmaPerancangan aplikasi data mining berbasis web dengan algoritma
Perancangan aplikasi data mining berbasis web dengan algoritmaAndreas Chandra
 

Mehr von Andreas Chandra (10)

Resume Andreas Chandra_online.pdf
Resume Andreas Chandra_online.pdfResume Andreas Chandra_online.pdf
Resume Andreas Chandra_online.pdf
 
Intro to machine learning
Intro to machine learningIntro to machine learning
Intro to machine learning
 
Financial analytics
Financial analyticsFinancial analytics
Financial analytics
 
Social Network Analysis dengan NetworkX
Social Network Analysis dengan NetworkXSocial Network Analysis dengan NetworkX
Social Network Analysis dengan NetworkX
 
Making The Data Talk
Making The Data TalkMaking The Data Talk
Making The Data Talk
 
Association rules in r
Association rules in rAssociation rules in r
Association rules in r
 
Tutorial penggunaan big query
Tutorial penggunaan big queryTutorial penggunaan big query
Tutorial penggunaan big query
 
Penerapan text mining menggunakan python
Penerapan text mining menggunakan pythonPenerapan text mining menggunakan python
Penerapan text mining menggunakan python
 
Intro to beautiful soup
Intro to beautiful soupIntro to beautiful soup
Intro to beautiful soup
 
Perancangan aplikasi data mining berbasis web dengan algoritma
Perancangan aplikasi data mining berbasis web dengan algoritmaPerancangan aplikasi data mining berbasis web dengan algoritma
Perancangan aplikasi data mining berbasis web dengan algoritma
 

Kürzlich hochgeladen

Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一ffjhghh
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusTimothy Spann
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiSuhani Kapoor
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxJohnnyPlasten
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAroojKhan71
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 

Kürzlich hochgeladen (20)

Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptx
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 

R for you

  • 1. R for You Andreas Chandra linkedin.com/in/chandraandreas
  • 2. Contents - Basic R - Data Structures - Reading Data - Charts - Function - Conditional Statements - Iteration - Grouping - Reshape - String Operations
  • 4. Basic R - Math Operation - Variable - Data type - Vectors - Calling Function - Missing Data
  • 5. Basic R - Math Basic Operation: 2 + 2 2 - 1 5 / 2 10 * 2 10 % 2 2 + (5 - 3)
  • 6. Variable X <- 10 X 10 <- Z Z A <- B <- 10 A B assign(“i”, 99) # Untuk menghapus variabel rm(B)
  • 7. Data Types ● Numeric ● Chars ● Dates ● Boolean
  • 9. Factor X <- c(“Januari”, “Februari”, “Maret”, “April”, “Januari”) X_factor <- as.factor(X) >X_factor [1] Januari Februari Maret April Januari Levels: April Februari Januari Maret
  • 12. Data Frames # create df <- data.frame() Function in df: nrow tail ncol class dim df[row, col] rownames df[, c(“pertama”, “kedua”)] head Df[2:3, ]
  • 13. Lists X <- list(1:3,4:6,7:9) names(X) None > names(X) <- c("pertama", "kedua", "ketiga") > X $pertama [1] 1 2 3 $kedua [1] 4 5 6 $ketiga [1] 7 8 9
  • 14. Matrices > X <- matrix(1:10, nrow = 5) > Y <- matrix(11:20, nrow = 5) > > X [,1] [,2] [1,] 1 6 [2,] 2 7 [3,] 3 8 [4,] 4 9 [5,] 5 10 > Y [,1] [,2] [1,] 11 16 [2,] 12 17 [3,] 13 18 [4,] 14 19 [5,] 15 20 > > Z <- X * Y > Z [,1] [,2] [1,] 11 96 [2,] 24 119 [3,] 39 144 [4,] 56 171 [5,] 75 200
  • 15. Arrays > arr <- array(1:12, dim = c(2, 3, 2)) > arr , , 1 [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 , , 2 [,1] [,2] [,3] [1,] 7 9 11 [2,] 8 10 12
  • 17. read.table > read.table(file, header = TRUE, sep = ",") #full detail > read.table(file, header = FALSE, sep = "", quote = ""'", + dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"), + row.names, col.names, as.is = !stringsAsFactors, + na.strings = "NA", colClasses = NA, nrows = -1, + skip = 0, check.names = TRUE, fill = !blank.lines.skip, + strip.white = FALSE, blank.lines.skip = TRUE, + comment.char = "#", + allowEscapes = FALSE, flush = FALSE, + stringsAsFactors = default.stringsAsFactors(), + fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)
  • 18. read.csv > read.csv(file, header = TRUE, sep = ",", quote = """, + dec = ".", fill = TRUE, comment.char = "")
  • 19. Excel (xlsx) read.xlsx(file, sheetIndex, sheetName=NULL, rowIndex=NULL, startRow=NULL, endRow=NULL, colIndex=NULL, as.data.frame=TRUE, header=TRUE, colClasses=NA, keepFormulas=FALSE, encoding="unknown")
  • 23. Scatterplot > library(ggplot2) > library(gapminder) > > data(gapminder) > > #create plot > plot(lifeExp ~ gdpPercap, data = gapminder) > #change scientific notation > options(scipen = 999)
  • 25. ggplot ggplot(gapminder, aes(x = lifeExp, y = gdpPercap)) + geom_point(aes(color = factor(continent)))
  • 27. Basic Function > hello_fun <- function(){ + print("hello world") + } > > hello_fun() [1] "hello world"
  • 28. Function with args > hello_fun <- function(name){ + print(sprintf("hello world %s", name)) + } > hello_fun(name = "Jakarta") [1] "hello world Jakarta"
  • 29. Default args > hello_fun <- function(name = "Bali"){ + print(sprintf("hello world %s", name)) + } > hello_fun() [1] "hello world Bali" > hello_fun(name = "Bandung") [1] "hello world Bandung"
  • 30. Return Values > hello_fun <- function(name = "Bali"){ + return(sprintf("hello world %s", name)) + } > greetings <- hello_fun(name = "Bandung") > greetings [1] "hello world Bandung"
  • 32. IF ElSE > grade_checker <- function(grade){ + if(grade > 7){ + return("Good") + }else if(grade > 4){ + return("Enough") + }else{ + return("Bad") + } + } > grade_checker(9) [1] "Good"
  • 33. Switch > class_switch <- function(class){ + switch(class, + "H" = "High", + "M" = "Medium", + "L" = "Low", + NA) + } > class_switch("H") [1] "High"
  • 35. For > names <- c("Ada", "Abu", "Abi", "Abe", "Abo") > for(name in names){ + print(name) + } [1] "Ada" [1] "Abu" [1] "Abi" [1] "Abe" [1] "Abo"
  • 36. While > names <- c("Ada", "Abu", "Abi", "Abe", "Abo") > index <- 1 > while (index <= length(names)){ + print(names[index]) + index = index + 1 + } [1] "Ada" [1] "Abu" [1] "Abi" [1] "Abe" [1] "Abo"
  • 38. apply > a_matrix <- matrix(1:9, nrow = 3) > a_matrix [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > > apply(a_matrix, 1, sum) [1] 12 15 18
  • 39. sapply, lapply > a_list <- list(A = matrix(1:9, 3), B = 1:9, C = matrix(1:6, 3)) > lapply(a_list, mean) $A [1] 5 $B [1] 5 $C [1] 3.5 > sapply(a_list, mean) A B C 5.0 5.0 3.5
  • 40. aggregate > data(diamonds) > head(diamonds) # A tibble: 6 x 10 carat cut color clarity depth table price x y z <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl> 1 0.230 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 2 0.210 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 3 0.230 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 4 0.290 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 5 0.310 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 6 0.240 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48 > > aggregate(price ~ cut + color, diamonds, mean) cut color price 1 Fair D 4291.061 2 Good D 3405.382 3 Very Good D 3470.467 4 Premium D 3631.293 5 Ideal D 2629.095 6 Fair E 3682.312 7 Good E 3423.644
  • 41. data.table > require(data.table) > head(diamonds) # A tibble: 6 x 10 carat cut color clarity depth table price x y z <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl> 1 0.230 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 2 0.210 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 3 0.230 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 4 0.290 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 5 0.310 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 6 0.240 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48 > diamonds_dt <- data.table(diamonds) > diamonds_dt[, sum(price), by = cut] cut V1 1: Ideal 74513487 2: Premium 63221498 3: Good 19275009 4: Very Good 48107623 5: Fair 7017600
  • 43. cbind & rbind > sport = c("Hoot", "Base", "Foot") > league = c("Hoot1", "Base2", "Foot3") > trophy = c("Hoot4", "Base5", "Foot6") > > trop1 = cbind(sport, league, trophy) > > trop2 <- data.frame(sport = c("Basket", "Golf"), + league = c("Laptop", "Notebook"), + trophy = c("rank1", "rank2")) > > trop3 = rbind(trop1, trop2) > > trop3 sport league trophy 1 Hoot Hoot1 Hoot4 2 Base Base2 Base5 3 Foot Foot3 Foot6 4 Basket Laptop rank1 5 Golf Notebook rank2
  • 44. merge > customer = data.frame(id = c(1,2,3), + name = c("Ada", "Adi", "Ade"), + address = c("Jkt", "Bdg", "Jog")) > order = data.frame(id = c(1,2,3), + order = c("Gayuung", "Sabun", "Pipa")) > trans = merge(customer, order, by.customer = c("id", "id")) > trans id name address order 1 1 Ada Jkt Gayuung 2 2 Adi Bdg Sabun 3 3 Ade Jog Pipa
  • 46. Reshape2 - melt > provinsi <- c("DKI Jakarta", "Jawa Barat", "Jawa Tengah") > SD <- c(100,200,300) > SMP <- c(120,210,310) > SMA <- c(130,220,320) > df <- data.frame(provinsi, SD, SMP, SMA) > melt(df, id = c("provinsi")) provinsi variable value 1 DKI Jakarta SD 100 2 Jawa Barat SD 200 3 Jawa Tengah SD 300 4 DKI Jakarta SMP 120 5 Jawa Barat SMP 210 6 Jawa Tengah SMP 310 7 DKI Jakarta SMA 130 8 Jawa Barat SMA 220 9 Jawa Tengah SMA 320
  • 49. paste Join 2 strings > paste("Andreas", "Chandra") > paste("DC", "2017", "01", "31", sep = "-") [1] "DC-2017-01-31" [1] "Hallo Andre" "Hey Chan" "Hallo Dra"
  • 50. sprintf > Name <- "Rio" > Age <- 20 > City <- "NYC" > > sprintf("I am %s, %d years old, Live in %s", Name, Age, City) [1] "I am Rio, 20 years old, Live in NYC" Printf format https://en.wikipedia.org/wiki/Printf_format_string
  • 51. Regular expression > library(stringr) > bad_john <- str_detect(string = names_list, "John") > good_john <- str_detect(string = names_list, ignore.case("John")) Please use (fixed|coll|regex)(x, ignore_case = TRUE) instead of ignore.case(x) > names_list[good_john] [1] "John Adams" "egi john" "John Ad" "john abs" > sum(bad_john) [1] 2 > sum(good_john) [1] 4
  • 53. Jared P. Lander, 2014, R for Everyone