在array中進(jìn)行隱式循環(huán)
lapply藏古,vapply和sapply不能直接用于matrix等array中晨继,這3個(gè)函數(shù)會(huì)將array視作vector烟阐,沿著column的方向?qū)⒚總€(gè)元素運(yùn)算一次,因此對(duì)于array結(jié)果的數(shù)據(jù)紊扬,我們需要使用apply()函數(shù)蜒茄。
apply(X, MARGIN, FUN, ...)
#MARGIN取1為row,取2為col
需要注意的是餐屎,apply函數(shù)的每一輪循環(huán)輸出結(jié)果都會(huì)被as.vector()強(qiáng)行coerce一次檀葛,然后再根據(jù)結(jié)果長短是否一致最終輸出為matrix或list。換句話說腹缩,如果隱循環(huán)每一輪本來輸出的是factor屿聋,被強(qiáng)行coerce之后輸出的就是character了空扎,最終結(jié)果是一個(gè)character matrix。
> x=matrix(1:16,nrow = 4)
> apply(x, 1, toString) #輸出的是4元素的string
[1] "1, 5, 9, 13" "2, 6, 10, 14" "3, 7, 11, 15" "4, 8, 12, 16"
在dataframe中進(jìn)行隱式循環(huán)
正如前文所說润讥,dataframe是list和array的結(jié)合體转锈,因此sapply和apply都可以用于dataframe,但依然要時(shí)刻留意格式coerce可能造成的隱患楚殿。
多參數(shù)同時(shí)進(jìn)入隱式循環(huán)
mapply()可以接受多個(gè)參數(shù)同時(shí)進(jìn)入循環(huán)撮慨,但其參數(shù)傳遞的順序需要注意。
#FUN是第一個(gè)傳遞進(jìn)入的參數(shù)
mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE,
USE.NAMES = TRUE)
參數(shù)化函數(shù)
Vectorize()是一個(gè)wrapper脆粥,可以將某些不能接受vector類型參數(shù)的函數(shù)(通常為自定義)轉(zhuǎn)化為能夠接受vector參數(shù)的函數(shù)甫煞。
split() 和 tapply()
書中介紹了split()函數(shù)和tapply函數(shù)。但個(gè)人認(rèn)為使用reshape2包中的melt()或cast()函數(shù)先把數(shù)據(jù)源處理了可能更好冠绢。抚吠。。弟胀。
split輸出一個(gè)list
# split能夠接受新的vector輸入
split(x, f, drop = FALSE, ...)
## Default S3 method:
split(x, f, drop = FALSE, sep = ".", lex.order = FALSE, ...)
split(x, f, drop = FALSE, ...) <- value
unsplit(value, f, drop = FALSE)
而tapply是針對(duì)ragged array進(jìn)行了優(yōu)化的一類apply函數(shù)楷力。
Apply a function to each cell of a ragged array, that is to each (non-empty) group of values
given by a unique combination of the levels of certain factors.
tapply(X, INDEX, FUN = NULL, ..., default = NA, simplify = TRUE)
#相當(dāng)于split X by INDEX中的factor levels then apply FUN
#INDEX參數(shù)會(huì)被強(qiáng)行as.factor()
tapply()的兩個(gè)wrapper
by()和aggregate()是tapply的兩個(gè)warpper函數(shù)。by()適用于dataframe孵户;而aggregate可用于dataframe萧朝,formula和ts三種數(shù)據(jù)類型。
by(data, INDICES, FUN, ..., simplify = TRUE)
## S3 method for class 'data.frame'
aggregate(x, by, FUN, ..., simplify = TRUE, drop = TRUE)