# 加總
x = list(c(1,2,3,4), c(5,6,7,8))
lapply(x, sum)
result:
[[1]]
[1] 10
[[2]]
[1] 26
x = list(c(1,2,3,4), c(5,6,7,8),c(1,3))
lapply(x, sum)
result:
[[1]]
[1] 10
[[2]]
[1] 26
[[3]]
[1] 4
#mean 平均
x = list(c(1,2,3,4), c(5,6,7,8),c(1,3))
lapply(x, mean)
result:
[[1]]
[1] 2.5
[[2]]
[1] 6.5
[[3]]
[1] 2
# c裡面的每個數字都加3
x = list(c(1,2,3,4), c(5,6,7,8),c(1,3))
lapply(x, function(i){i+3})
result:
[[1]]
[1] 4 5 6 7
[[2]]
[1] 8 9 10 11
[[3]]
[1] 4 6
# 呼叫每個c的第2個數字
x = list(c(1,2,3,4), c(5,6,7,8),c(1,3))
lapply(x, function(i){i[2]})
result:
[[1]]
[1] 2
[[2]]
[1] 6
[[3]]
[1] 3
# 用途(結果)同上
x = list(c(1,2,3,4), c(5,6,7,8),c(1,3))
a = function(i){i[2]}
lapply(x, a)
result:
[[1]]
[1] 2
[[2]]
[1] 6
[[3]]
[1] 3
# 求每個陣列的平均
m1 = matrix(1:4, byrow=TRUE, nrow=2)
m2 = matrix(5:8, byrow=TRUE, nrow=2)
li = list(m1, m2)
li
result:
[[1]]
[,1] [,2]
[1,] 1 2
[2,] 3 4
[[2]]
[,1] [,2]
[1,] 5 6
[2,] 7 8
lapply(li, mean)
result:
[[1]]
[1] 2.5
[[2]]
[1] 6.5
#--sapply--(產生比lappy簡化的結果)-------------------
x = list(c(1,2,3,4), c(5,6,7,8))
sapply(x, sum)
result:
[1] 10 26
#與lapply 做比較
x = list(c(1,2,3,4), c(5,6,7,8))
lapply(x, sum)
result:
[[1]]
[1] 10
[[2]]
[1] 26
#--sapply------------------------------------
m1 = matrix(1:4, byrow=TRUE, nrow=2)
m2 = matrix(5:8, byrow=TRUE, nrow=2)
m1
m2
result:
>m1
[,1] [,2]
[1,] 1 2
[2,] 3 4
> m2
[,1] [,2]
[1,] 5 6
[2,] 7 8
li = list(m1, m2) # list 將兩個陣列包起來
li
result:
[[1]]
[,1] [,2]
[1,] 1 2
[2,] 3 4
[[2]]
[,1] [,2]
[1,] 5 6
[2,] 7 8
sapply(li, mean) # 求兩個陣列的平均
result:
[1] 2.5 6.5
sapply(li,function(e) e[1,]) # 利用function 求list中'列'的值
result:
[,1] [,2]
[1,] 1 5
[2,] 2 6
#---Apply---------------------------------------------------
m = matrix(1:4, byrow=TRUE, nrow=2)
m
result:
[,1] [,2]
[1,] 1 2
[2,] 3 4
apply(m, 1, sum) #加總列的值
result:
[1] 3 7
apply(m, 2, sum) #加總行的值
result:
[1] 4 6
rowSums(m) #加總列的值
result:
[1] 3 7
colSums(m) #加總行的值
result:
[1] 4 6
#---tapply----分組平均計算------------------------------
x = c(80,70,59,88,72,57) # 值
t = c(1,1,2,1,1,2) # 類別
tapply(x,t, mean) # 求平均
result:
1 2
77.5 58.0
x = c(80,70,59,88,72,57)
a = c("m","f","m","m","f","f") # 可替換標題,更改群組(內值)個數
tapply(x,a, mean)
result:
f m
66.33333 75.66667
# 例題---使用iris(Sepal.Length、Species)求分組平均計算
head(iris)
data(iris)
tapply(iris$Sepal.Length, iris$Species, mean)
#---mapply---------------------------------
rep(1,3), rep(2,4), rep(3,5) # rep(值,重複次數)
mapply(rep, 1:3, 3:5) # rep, 值的範圍, 重複次數的範圍(比較少用)
result:
[[1]]
[1] 1 1 1
[[2]]
[1] 2 2 2 2
[[3]]
[1] 3 3 3 3 3
#---練習題---求mtcars中cyl & geal的平均mpg---------------------
data(mtcars)
tapply(mtcars$mpg, list(mtcars$cyl,mtcars$gear), mean)
# tapply(欲計算的值, list(資料集$欄位A,資料集$欄位B),function)
result:
3 4 5
4 21.50 26.925 28.2
6 19.75 19.750 19.7
8 15.05 NA 15.4
沒有留言:
張貼留言