前言:
微博參與話題 #給你四年時間你也學(xué)不會生信#
Divide into Groups and Reassemble | 重新組合
函數(shù)split()可以按照分組因子,把向量,矩陣和數(shù)據(jù)框進(jìn)行適當(dāng)?shù)姆纸M。它的返回值是一個列表,代表分組變量每個水平的觀測。這個列表可以使用sapply(),lappy()進(jìn)行處理(apply – combine步驟),得到問題的最終結(jié)果。
只是分組,既可以對向量分組,也可以對數(shù)據(jù)框分組
Usage
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)
Arguments | 參數(shù)
- x: 一個待分組的向量或者data frame
- f: 函數(shù),一個factor或者list(如果list中元素交互作用于分組中),以此為規(guī)則將x分組
- drop: 邏輯值,如果f中的某一個level沒有用上則被棄用
- value: 一個儲存向量的list,其形式類似于分組完成之后返回的那個list
Example | 例子
> d <- data.frame(gender=c("M","M","F","M","F","F"),age=c(47,59,21,32,33,24),income=c(55000,88000,32450,76500,123000,45650), over25=rep(c(1,1,0), times=2))
> d
gender age income over25
1 M 47 55000 1
2 M 59 88000 1
3 F 21 32450 0
4 M 32 76500 1
5 F 33 123000 1
6 F 24 45650 0
> split(d$income, list(d$gender,d$over25)) #將income按照gender、over25分組
$`F.0`
[1] 32450 45650
$M.0
numeric(0)
$F.1
[1] 123000
$M.1
[1] 55000 88000 76500
參考資料: