R studio 頁面介紹
R studio主要分為四大區塊
1. 左上區為R Script,若想新增編輯頁面可點選左上角的「+」選R Script(windows快捷鍵為ctrl + shift + N , Mac為 command + shift + N)。
2. 左下區R的執行介面(Console),在編輯區塊所執行的指令都會在左下角顯現,也可以在此執行指令。
3. 右上區(Environment)像是倉庫一樣,儲存了匯入及創造出宣告的資料,執行過的命令也會記錄下來。
4. 右下區則包含Files、Plots、Packages、Help、Viewer,可以查看繪製的圖也可以查詢不懂的指令。
通常給R 的指令分成兩種,一個 expression,或是一個 assignment。
# 加 ; 減 ; 乘 ; 除 (這些都是Expression)
1 + 3 ; 10 - 8 ; 3 * 2 ; 6 / 3
## [1] 4
## [1] 2
## [1] 6
## [1] 2
# 3的平方 ; 3的1/3次方 ; 根號2
3 ^ 2 ; 3 ^ (1/3) ; sqrt(2)
## [1] 9
## [1] 1.44225
## [1] 1.414214
# 以e為底取log ; # log2代表以2為底
log(65) ; log2(10)
## [1] 4.174387
## [1] 3.321928
pi ; exp(1)
## [1] 3.141593
## [1] 2.718282
# 四捨五入 ; # 四捨五入到小數點第二位 ; # 無條件捨去 ; # 無條件進位 ; # 取絕對值
round(4.7) ; round(4.786, 2) ; floor(4.7) ; ceiling(4.7) ; abs(-4.7)
## [1] 5
## [1] 4.79
## [1] 4
## [1] 5
## [1] 4.7
x <- c( 1 , 2 , 3 , 4 ) # 也可以寫成 x <- 1:4 (這個就是assignment)
# 總和 # 平均數 # 中位數 # 變異數 # 樣本標準差
sum(x) ; mean(x) ; median(x) ; var(x) ; sd(x) ; summary(x)
## [1] 10
## [1] 2.5
## [1] 2.5
## [1] 1.666667
## [1] 1.290994
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.00 1.75 2.50 2.50 3.25 4.00
cumsum(x) # 累加
## [1] 1 3 6 10
cumprod(x) # 累乘(可以算階乘)
## [1] 1 2 6 24
#結構
str(iris)
## 'data.frame': 150 obs. of 5 variables:
## $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
## $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
## $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
## $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
## $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#類別
class(iris)
## [1] "data.frame"
#屬性
attributes(iris)
## $names
## [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
## [5] "Species"
##
## $class
## [1] "data.frame"
##
## $row.names
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
## [18] 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
## [35] 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
## [52] 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
## [69] 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
## [86] 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
## [103] 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
## [120] 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
## [137] 137 138 139 140 141 142 143 144 145 146 147 148 149 150
class(c(7,8,9))
## [1] "numeric"
class(c("葉哥好師","嗨嗨"))
## [1] "character"
class(c(TRUE,FALSE))
## [1] "logical"
c(1,2,3)+c(1:3)
## [1] 2 4 6
2+c(1,2,3)
## [1] 3 4 5
c(1,2)+c(1,2,3,4)
## [1] 2 4 4 6
c(1,3)+c(1,2,3)
## Warning in c(1, 3) + c(1, 2, 3): 較長的物件長度並非較短物件長度的倍數
## [1] 2 5 4
x <- c(1,2,3) ; y <- c(3,6,9)
x+y ; x*y ; y/x
## [1] 4 8 12
## [1] 3 12 27
## [1] 3 3 3
## 1 ~ 12的打法可以打 :
## == 是用來判斷有沒有相等
1:12
## [1] 1 2 3 4 5 6 7 8 9 10 11 12
(x1 = matrix(1 : 12 ,ncol = 6) )
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1 3 5 7 9 11
## [2,] 2 4 6 8 10 12
(x2 = matrix(1 : 12 ,ncol = 6, byrow = T) )
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1 2 3 4 5 6
## [2,] 7 8 9 10 11 12
(y1 = matrix(1 : 4 ,nrow = 2) )
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
(y2 = matrix(1 : 4 ,nrow = 2, byrow = T) )
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
t(x1) # 轉置(transpose)
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
## [3,] 5 6
## [4,] 7 8
## [5,] 9 10
## [6,] 11 12
solve(y1)
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
x1
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1 3 5 7 9 11
## [2,] 2 4 6 8 10 12
t(x1) %*% x1
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 5 11 17 23 29 35
## [2,] 11 25 39 53 67 81
## [3,] 17 39 61 83 105 127
## [4,] 23 53 83 113 143 173
## [5,] 29 67 105 143 181 219
## [6,] 35 81 127 173 219 265
x1 * x1 # t(x1) * x1 不能跑,因為兩個物件維度不一樣
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1 9 25 49 81 121
## [2,] 4 16 36 64 100 144
data <- data.frame(x1=c(1,2,3), #若要換行則此逗號要擺這
x2=c('a','b','c'))
data ; class(data)
## x1 x2
## 1 1 a
## 2 2 b
## 3 3 c
## [1] "data.frame"
data <- data.frame(x1=c(1,2,3,4),
x2=c('a','b','c'))
## Error in data.frame(x1 = c(1, 2, 3, 4), x2 = c("a", "b", "c")) :
arguments imply differing number of rows: 4, 3
lst <- list(A=c(1:5),
B=c('a','b'))
lst
## $A
## [1] 1 2 3 4 5
##
## $B
## [1] "a" "b"
## Data.frame
data <- data.frame(Date=c('7/23','7/23'),
Come=c(T,F),
Time=c(3,6))
data
## Date Come Time
## 1 7/23 TRUE 3
## 2 7/23 FALSE 6
## 好,我要從data中取出日期的變數(欄位、向量、抽屜)
data$Date ; data[,1]
## [1] 7/23 7/23
## Levels: 7/23
## [1] 7/23 7/23
## Levels: 7/23
## 好,我要從data中取出是否會來的變數(欄位、向量、抽屜)
data$Come ; data[,2]
## [1] TRUE FALSE
## [1] TRUE FALSE
## 好,我要從data中取出 '6'
data[2,3]
## [1] 6
## List
data <- list(Date=c('7/23','7/24','7/25','7/26'),
Come=c(T,F),
Time=c(3,6))
data
## $Date
## [1] "7/23" "7/24" "7/25" "7/26"
##
## $Come
## [1] TRUE FALSE
##
## $Time
## [1] 3 6
## 好,我要從data中取出日期的變數(欄位、向量、抽屜)
## 只是今天衣櫃的每個抽屜長度可以不一樣
data$Date
## [1] "7/23" "7/24" "7/25" "7/26"
data[1] # 仍然是list格式
## $Date
## [1] "7/23" "7/24" "7/25" "7/26"
data[[1]]
## [1] "7/23" "7/24" "7/25" "7/26"
data[[1]][2]
## [1] "7/24"
## NA常常就像這樣任性的存在
x <- c(1,2,3,NA,5)
y <- c(1,2,NA,4,5)
## NA只要碰到加減乘除就會無效
x + y
## [1] 2 4 NA NA 10
mean(x)
## [1] NA
## 只要把缺憾移除掉人生就美好多了
mean(x,na.rm=T)
## [1] 2.75
## 通常NA有規則可以填補我們就會補起來
x[4] <- 4
## 但往往你需要更聰明的方式去補而不是這樣傻傻的數啊 !!
## is.na可以回傳變數哪一個位置為NA
is.na(y)
## [1] FALSE FALSE TRUE FALSE FALSE
y[ is.na(y) ] <- 3
my.money <- c(0,100,Inf) ; your.money <- c(-Inf,10,0)
my.money+your.money
## [1] -Inf 110 Inf
my.money/your.money ## 我也不知道為什麼 Inf/0會=Inf,可能要問問助教
## [1] 0 10 Inf
0/0 ; 1/0-1/0
## [1] NaN
## [1] NaN
head(iris,3) # 預設為看前六行
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
tail(iris,3)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 148 6.5 3.0 5.2 2.0 virginica
## 149 6.2 3.4 5.4 2.3 virginica
## 150 5.9 3.0 5.1 1.8 virginica
data = iris[1:6, 1:5]
data ; class(data)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
## [1] "data.frame"
names(data) #看現在欄位的名字
## [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
## [5] "Species"
names(data) = c('花萼長', '花萼寬', '花瓣長', '花瓣寬', '品種')
names(data)
## [1] "花萼長" "花萼寬" "花瓣長" "花瓣寬" "品種"
# 刪除第五欄
data[,-5]
## 花萼長 花萼寬 花瓣長 花瓣寬
## 1 5.1 3.5 1.4 0.2
## 2 4.9 3.0 1.4 0.2
## 3 4.7 3.2 1.3 0.2
## 4 4.6 3.1 1.5 0.2
## 5 5.0 3.6 1.4 0.2
## 6 5.4 3.9 1.7 0.4
new = c('a','b','c','d','e','f')
cbind(data, new) # 增加第六欄
## 花萼長 花萼寬 花瓣長 花瓣寬 品種 new
## 1 5.1 3.5 1.4 0.2 setosa a
## 2 4.9 3.0 1.4 0.2 setosa b
## 3 4.7 3.2 1.3 0.2 setosa c
## 4 4.6 3.1 1.5 0.2 setosa d
## 5 5.0 3.6 1.4 0.2 setosa e
## 6 5.4 3.9 1.7 0.4 setosa f
# 刪除第六列
data[-6,]
## 花萼長 花萼寬 花瓣長 花瓣寬 品種
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
new = c(5.2 , 3.1, 1.1, 0.3, 'setosa')
rbind(data, new) # 增加第七列
## 花萼長 花萼寬 花瓣長 花瓣寬 品種
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
## 7 5.2 3.1 1.1 0.3 setosa
dim(data)
## [1] 6 5
str(data) # attributes(data)
## 'data.frame': 6 obs. of 5 variables:
## $ 花萼長: num 5.1 4.9 4.7 4.6 5 5.4
## $ 花萼寬: num 3.5 3 3.2 3.1 3.6 3.9
## $ 花瓣長: num 1.4 1.4 1.3 1.5 1.4 1.7
## $ 花瓣寬: num 0.2 0.2 0.2 0.2 0.2 0.4
## $ 品種 : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1
data$品種 = '某一種花'
data
## 花萼長 花萼寬 花瓣長 花瓣寬 品種
## 1 5.1 3.5 1.4 0.2 某一種花
## 2 4.9 3.0 1.4 0.2 某一種花
## 3 4.7 3.2 1.3 0.2 某一種花
## 4 4.6 3.1 1.5 0.2 某一種花
## 5 5.0 3.6 1.4 0.2 某一種花
## 6 5.4 3.9 1.7 0.4 某一種花
## 選擇 花萼長 >= 5 的資料(列)
(index = data$花萼長 >= 5)
## [1] TRUE FALSE FALSE FALSE TRUE TRUE
data[index,]
## 花萼長 花萼寬 花瓣長 花瓣寬 品種
## 1 5.1 3.5 1.4 0.2 某一種花
## 5 5.0 3.6 1.4 0.2 某一種花
## 6 5.4 3.9 1.7 0.4 某一種花
X ; Y #請宣告兩個變量X、Y,分別代表下面的X矩陣和Y矩陣
## [,1] [,2]
## [1,] 1 1
## [2,] 0 2
## [3,] 1 0
## [,1]
## [1,] 13
## [2,] -2
## [3,] 1
?mean
??mean
help(mean)
length(c(1:10))
## [1] 10
set.seed(10)
(x <- sample(10, 7))
## [1] 6 3 4 5 1 2 7
sort(x)
## [1] 1 2 3 4 5 6 7
y <- sort(x)
order(x)
## [1] 5 6 2 3 4 1 7
rank(x)
## [1] 6 3 4 5 1 2 7
x[order(x)]
## [1] 1 2 3 4 5 6 7
y
## [1] 1 2 3 4 5 6 7
y[rank(x)]
## [1] 6 3 4 5 1 2 7
x
## [1] 6 3 4 5 1 2 7
seq(from = 1, to = 9, by = 2) ## seq(1,9,2)
## [1] 1 3 5 7 9
seq(from = 9, to = 1, by = -2) ## seq(9,1,-2)
## [1] 9 7 5 3 1
rep( seq(from = 1, to = 9, by = 2) , times= 2)
## [1] 1 3 5 7 9 1 3 5 7 9
rep( seq(from = 1, to = 9, by = 2) , each= 2)
## [1] 1 1 3 3 5 5 7 7 9 9
rep(seq(from = 1, to = 9, by = 2) , each = 3 , times = 2)
## [1] 1 1 1 3 3 3 5 5 5 7 7 7 9 9 9 1 1 1 3 3 3 5 5 5 7 7 7 9 9 9
3 > 2 ; 3 < 2
## [1] TRUE
## [1] FALSE
3 >= 5 ; 3 <= 5
## [1] FALSE
## [1] TRUE
# 你可以key 2 = 3 看看
2 == 3 ; 2 != 3
## [1] FALSE
## [1] TRUE
data
## 花萼長 花萼寬 花瓣長 花瓣寬 品種
## 1 5.1 3.5 1.4 0.2 某一種花
## 2 4.9 3.0 1.4 0.2 某一種花
## 3 4.7 3.2 1.3 0.2 某一種花
## 4 4.6 3.1 1.5 0.2 某一種花
## 5 5.0 3.6 1.4 0.2 某一種花
## 6 5.4 3.9 1.7 0.4 某一種花
data$花瓣長 < 5 & data$花瓣長 > 4.6 # 知道true and false 就可以抓出特定資料
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
data$花瓣長 > 5 & data$花瓣寬 == 0.2
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
## 看物件是否有包含在裡面
c(2,5) %in% c(1:3)
## [1] TRUE FALSE
ifelse( 3 > 2 , 3 + 2 , 3 - 2 ) #如果3>2成立,則執行3+2,否則執行3-2
## [1] 5
if(3 < 2){
3 + 2 # 如果 "3 < 2" 為TRUE,則執行3 + 2
}else if (3 == 2){
3 * 2 # 否則如果 "3 == 2" 為TRUE,則執行3 * 2
}else{
3 - 2 # 如果 "3 < 2"和 "3 == 2" 皆為FALSE,則執行3 - 2
}
## [1] 1
for(variable in iterator) {Expressions}
variable : 宣告一個變量
iterator : 疊代器,用來宣告遞迴過程中變量要依序變換的值,
也就宣告一個遞迴用的「向量」Expressions : 可以跟variable有關或無關的運算
x <- 0
for(i in 1:5){
x <- x + i
print(x)
}
## [1] 1
## [1] 3
## [1] 6
## [1] 10
## [1] 15
x
## [1] 15
which(c('a', 'b', 'c') == 'b')
## [1] 2
set.seed(1)
(x = rnorm(20))
## [1] -0.62645381 0.18364332 -0.83562861 1.59528080 0.32950777
## [6] -0.82046838 0.48742905 0.73832471 0.57578135 -0.30538839
## [11] 1.51178117 0.38984324 -0.62124058 -2.21469989 1.12493092
## [16] -0.04493361 -0.01619026 0.94383621 0.82122120 0.59390132
which(x > 1) # 誰大於1
## [1] 4 11 15
sum(x > 1) # 有多少筆大於1
## [1] 3
x[x>1] # 挑出大於1的
## [1] 1.595281 1.511781 1.124931
cust.mean <- function(x){
mean.result <- sum(x)/length(x)
return(mean.result)
}
cust.mean(1:10)
## [1] 5.5
## It's same
mean(1:10)
## [1] 5.5
x <- c('ABC-88','WTF-978','CBD-0857')
## 計算字數
nchar(x)
## [1] 6 7 8
## 切割英文跟數字
strsplit(x, split = '-')
## [[1]]
## [1] "ABC" "88"
##
## [[2]]
## [1] "WTF" "978"
##
## [[3]]
## [1] "CBD" "0857"
## 字串的擷取
substr(x = x[1] , start = 1 , stop = 5)
## [1] "ABC-8"
## 字串的剪貼
paste(substr(x[2],1,7),substr(x[3],5,7), sep = '-')
## [1] "WTF-978-085"
x <- c(1,2,3)
as.character(x)
## [1] "1" "2" "3"
x <- c('1','2')
as.numeric(x)
## [1] 1 2
y <- c('1','a')
as.numeric(y)
## Warning: 強制變更過程中產生了 NA
## [1] 1 NA
z <- factor(c('a','b','c'))
as.numeric(z)
## [1] 1 2 3
z1 <- factor(c('a','b','c'),levels=c('c','b','a'))
as.numeric(z1)
## [1] 3 2 1
w <- factor(c('4','5','6'))
as.numeric(w)
## [1] 1 2 3
w <- factor(c('4','5','6'))
as.numeric( as.character(w) )
## [1] 4 5 6
x <- c(1,2,3)
as.factor(x)
## [1] 1 2 3
## Levels: 1 2 3
y <- c('a','b','c')
as.factor(y)
## [1] a b c
## Levels: a b c
getwd()
## [1] "/Users/chenchunyen/Documents/Projects/R工作坊教材"
# Windows
setwd("C:\\Users")
# Mac
setwd("/Users/chenchunyen/Desktop/")
demo <- iris
# 直接將demo.csv存至剛剛設定的工作目錄
write.csv(demo,"demo.csv")
# 將demo.csv存至指定路徑
write.csv(demo,"/Users/chenchunyen/Desktop/Code/Program/Workshop/demo.csv")
# 將剛剛匯出的demo.csv檔讀進來
data <- read.csv("/Users/chenchunyen/Desktop/Code/Program/Workshop/demo.csv")
# or
data <- read.csv(file.choose())
data <- read.table("/Users/chenchunyen/Desktop/Code/Program/Workshop/demo.csv",header = T,sep = ',')
s <- scan()
> s <- scan()
1: 5
2: 4
3: 0
4: 0
5:
Read 4 items
> s
[1] 5 4 0 0
data <- read.csv("demo.csv",fileEncoding = 'big5')
data <- read.csv("demo.csv",fileEncoding = 'utf8')
par(mfrow = c(2,2)) # 將頁面切成四等份
x = rnorm(50)
plot(x)
boxplot(x)
hist(x) # x 軸當成連續
barplot(x) # x 軸當成類別
par(mfrow = c(2,2))
par(family="STKaiti") #顯示中文(可換各種字型)
plot(x, main = 'plot 指令可以放兩個維度')
boxplot(x, ylim = c(-3,3))
hist(x, xlab = '我是x軸', ylab = '我是y軸', breaks = seq(-4, 4, 0.05), prob = T); lines(density(x, width = 1))
barplot(x, col =2)
plot(1:10, rep(1, 10), pch=20, col=1:10, cex=5, xlab="", ylab="")
text(1:10, rep(1.2, 10), labels=1:10)
plot(iris[,1], iris[,2], pch = 16 ,col =
ifelse(iris[,5] == 'setosa', 'red',
ifelse(iris[,5] == 'versicolor', 'blue', 'green')) )
par(family = 'STKaiti')
x = iris[,1] ; y = iris[,2]
plot(y~x, xlim=c(1.5,9), ylim=c(1.5,9), type="n", main = '迴歸直線')
points(x[1:50], y[1:50], col="red")
points(x[51:100], y[51:100], col="blue")
points(x[101:150], y[101:150], col="green")
abline(lm(y~x)) # 增加線
pairs(iris[,1:4], col=as.integer(iris[,5])+1, panel=panel.smooth)
library(scatterplot3d)
z <- seq(-10, 10, 0.01)
x <- cos(z)
y <- sin(z)
scatterplot3d(x, y, z, highlight.3d=TRUE, col.axis="blue",
col.grid="lightblue", main="scatterplot3d - 1", pch=20)
# 安裝套件
install.packages('dplyr')
# 載入套件
library(dplyr) #注意,重新開啟R之後,要再使用dplyr套件的話,都要再重新載入套件:library(dplyr)
# 挑選資料欄位
temp <- select(data, 鄉鎮市區, 交易標的)
# 剔除資料欄位
temp <- select(data, -鄉鎮市區)
# 挑我們練習的欄位
data.new <- select(data,-c(非都市土地使用分區, 非都市土地使用編定, 交易筆棟數,
移轉層次, 建物現況格局.房:建物現況格局.隔間,
車位類別, 備註, 編號))
# or
data.new <- select(data,-c(6,7,9,10,17:20,24,27,28))
data.wenshan <- filter(data.new, 鄉鎮市區=='文山區')
head(data.wenshan)
data.new <- mutate(data.new,建物坪數=建物移轉總面積平方公尺*0.3025,
土地坪數=土地移轉總面積平方公尺*0.3025)
# 注意建物坪數=0 算出來會是Inf
mutate(data.new,坪價=總價元/建物坪數)
# 避開建物坪數=0
data.new <- mutate(data.new, 坪價=ifelse(建物坪數==0, 0, 總價元/建物坪數))
arrange(data.new,坪價)
arrange(data.new,desc(坪價))
# ?mean 有NA時去計算平均數會得到NA的結果
# na.rm幫助我們把na去除掉!
summarise(data.new,
平均坪價 = mean(坪價,na.rm = T))
## 平均坪價
## 1 523112.5
# 也可以一次計算多個彙總函式
summarise(data.new,
平均坪價 = mean(坪價,na.rm = T),
坪價中位數 = median(坪價,na.rm = T),
最貴 = max(坪價,na.rm = T),
最便宜 = min(坪價,na.rm = T))
## 平均坪價 坪價中位數 最貴 最便宜
## 1 523112.5 479432.1 165289256 0
result <- summarise(group_by(data.new,鄉鎮市區),
平均坪價 = mean(坪價,na.rm = T),
坪價中位數 = median(坪價,na.rm = T),
最貴 = max(坪價,na.rm = T),
最便宜 = min(坪價,na.rm = T))
# 發現鄉鎮市區欄位中有很多的異常值,要把它去除
# 動動腦思考看看要怎麼去除
result$鄉鎮市區 <- as.character(result$鄉鎮市區)
result <- filter(result,nchar(result$鄉鎮市區)==3)
# 計算筆數有蠻多種方式: n(), length(), tally
summarise(group_by(data.new,鄉鎮市區),
交易筆數a=n(),
交易筆數b=length(建物坪數),
交易筆數c=length(坪價))
## # A tibble: 12 x 4
## 鄉鎮市區 交易筆數a 交易筆數b 交易筆數c
## <fct> <int> <int> <int>
## 1 北投區 842 842 842
## 2 大安區 455 455 455
## 3 大同區 192 192 192
## 4 南港區 222 222 222
## 5 內湖區 531 531 531
## 6 士林區 435 435 435
## 7 松山區 292 292 292
## 8 萬華區 416 416 416
## 9 文山區 451 451 451
## 10 信義區 315 315 315
## 11 中山區 611 611 611
## 12 中正區 227 227 227
tally(group_by(data.new,鄉鎮市區))
## # A tibble: 12 x 2
## 鄉鎮市區 n
## <fct> <int>
## 1 北投區 842
## 2 大安區 455
## 3 大同區 192
## 4 南港區 222
## 5 內湖區 531
## 6 士林區 435
## 7 松山區 292
## 8 萬華區 416
## 9 文山區 451
## 10 信義區 315
## 11 中山區 611
## 12 中正區 227
ggplot(data=…, aes(x=…, y=…)) +
geom_xxx(…) + stat_xxx(…) + facet_xxx(…) + …
library(dplyr)
library(ggplot2)
stw <- starwars %>% filter(gender == 'male' | gender == 'female') %>%
group_by(gender,eye_color) %>% summarise(amount = n()) %>%
mutate(rate = round(amount/sum(amount),2) )
stw %>%
ggplot(aes(x = gender ,y = rate ,fill = eye_color)) +
geom_bar(stat = 'identity', position = 'stack')+ # stack為類別堆疊
theme(text=element_text(size = 15, family = "STHeiti"))
library(dplyr)
library(ggplot2)
d <- iris # Full data set
d_bg <- d[, -5] # Background Data - full without the 5th column (Species)
x2 = ggplot(d, aes(x = Sepal.Width, fill = Species)) + #設定x軸,用種類當
geom_histogram(data = d_bg, fill = "grey", alpha = .5) +
geom_histogram(colour = "black") +
facet_wrap(~ Species) +
guides(fill = FALSE) + # to remove the legend
theme_bw() # for clean look overall
x2
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
mtcars$car = row.names(mtcars)
p = ggplot(mtcars, aes(x=car, y=mpg, fill=mpg)) +
geom_bar(stat='identity') +theme_light() +
scale_fill_gradient(low='red', high='white', limits=c(5,40)) +
theme(axis.title.y=element_text(angle=0))
# p + theme(axis.text.x = element_text(angle=45, vjust = 1, hjust=1))
x3 = p + coord_polar()
x3
library(rlist)
library(dplyr)
jsontext <- '[
{ "Name" : "Ken",
"Age" : 24,
"Interests" : [
"reading",
"music",
"movies"
],
"Expertise" : {
"R": 2,
"CSharp": 4,
"Python" : 3
}
},
{
"Name" : "James",
"Age" : 25,
"Interests" : [
"sports",
"music"
],
"Expertise" : {
"R" : 3,
"Java" : 2,
"Cpp" : 5
}
},
{
"Name" : "Penny",
"Age" : 24,
"Interests" : [
"movies",
"reading"
],
"Expertise" : {
"R" : 1,
"Cpp" : 4,
"Python" : 2
}
}
]'
people <- list.parse(jsontext, "json")
str(people)
## List of 3
## $ :List of 4
## ..$ Name : chr "Ken"
## ..$ Age : int 24
## ..$ Interests:List of 3
## .. ..$ : chr "reading"
## .. ..$ : chr "music"
## .. ..$ : chr "movies"
## ..$ Expertise:List of 3
## .. ..$ R : int 2
## .. ..$ CSharp: int 4
## .. ..$ Python: int 3
## $ :List of 4
## ..$ Name : chr "James"
## ..$ Age : int 25
## ..$ Interests:List of 2
## .. ..$ : chr "sports"
## .. ..$ : chr "music"
## ..$ Expertise:List of 3
## .. ..$ R : int 3
## .. ..$ Java: int 2
## .. ..$ Cpp : int 5
## $ :List of 4
## ..$ Name : chr "Penny"
## ..$ Age : int 24
## ..$ Interests:List of 2
## .. ..$ : chr "movies"
## .. ..$ : chr "reading"
## ..$ Expertise:List of 3
## .. ..$ R : int 1
## .. ..$ Cpp : int 4
## .. ..$ Python: int 2
list.map(people, c(Name,Age))
## [[1]]
## [1] "Ken" "24"
##
## [[2]]
## [1] "James" "25"
##
## [[3]]
## [1] "Penny" "24"
list.map(people, sum(as.numeric(Expertise)))
## [[1]]
## [1] 9
##
## [[2]]
## [1] 10
##
## [[3]]
## [1] 7
list.mapv(people, Age)
## [1] 24 25 24
list.select(people, Name, Age)
## [[1]]
## [[1]]$Name
## [1] "Ken"
##
## [[1]]$Age
## [1] 24
##
##
## [[2]]
## [[2]]$Name
## [1] "James"
##
## [[2]]$Age
## [1] 25
##
##
## [[3]]
## [[3]]$Name
## [1] "Penny"
##
## [[3]]$Age
## [1] 24
list.iter(people, cat(Name, ":", Age, "\n"))
## Ken : 24
## James : 25
## Penny : 24
str(list.filter(people, Age >= 25))
## List of 1
## $ :List of 4
## ..$ Name : chr "James"
## ..$ Age : int 25
## ..$ Interests:List of 2
## .. ..$ : chr "sports"
## .. ..$ : chr "music"
## ..$ Expertise:List of 3
## .. ..$ R : int 3
## .. ..$ Java: int 2
## .. ..$ Cpp : int 5
##想知道誰年紀大於等於25歲,可以用以下方式找出
list.mapv(list.filter(people, Age >= 25), Name)
## [1] "James"
##也可以利用dplyr最實用的功能之一 %>% 來運算
people %>%
list.filter(Age >= 25) %>%
list.mapv(Name)
## [1] "James"
list.all(people, "R" %in% names(Expertise))
## [1] TRUE
list.any(people, "Python" %in% names(Expertise))
## [1] TRUE
people %>%
list.sort(Age) %>%
list.select(Name, Age) %>%
str
## List of 3
## $ :List of 2
## ..$ Name: chr "Ken"
## ..$ Age : int 24
## $ :List of 2
## ..$ Name: chr "Penny"
## ..$ Age : int 24
## $ :List of 2
## ..$ Name: chr "James"
## ..$ Age : int 25
##
##
##
## -----
## May the force be with you .
## ------
## \
## \
## ____
## _.' : `._
## .-.'`. ; .'`.-.
## __ / : ___\ ; /___ ; \ __
## ,'_ ""--.:__;".-.";: :".-.":__;.--"" _`,
## :' `.t""--.. '<@.`;_ ',@>` ..--""j.' `;
## `:-.._J '-.-'L__ `-- ' L_..-;'
## "-.__ ; .-" "-. : __.-"
## L ' /.------.\ ' J
## "-. "--" .-"
## __.l"-:_JL_;-";.__
## .-j/'.; ;"""" / .'\"-.
## .' /:`. "-.: .-" .'; `.
## .-" / ; "-. "-..-" .-" : "-.
## .+"-. : : "-.__.-" ;-._ \
## ; \ `.; ; : : "+. ;
## : ; ; ; : ; : \:
## ; : ; : ;: ; :
## : \ ; : ; : ; / ::
## ; ; : ; : ; : ;:
## : : ; : ; : : ; : ;
## ;\ : ; : ; ; ; ;
## : `."-; : ; : ; / ;
## ; -: ; : ; : .-" :
## :\ \ : ; : \.-" :
## ;`. \ ; : ;.'_..-- / ;
## : "-. "-: ; :/." .' :
## \ \ : ;/ __ :
## \ .-`.\ /t-"" ":-+. :
## `. .-" `l __/ /`. : ; ; \ ;
## \ .-" .-"-.-" .' .'j \ / ;/
## \ / .-" /. .'.' ;_:' ;
## :-""-.`./-.' / `.___.'
## \ `t ._ / bug
## "-.t-._:'
##