split允许根据data.frame因子/组变量将向量或a分为多个桶。进入桶中的这种通风采用列表的形式,然后可用于进行逐组计算(for循环或lapply/ sapply)。
第一个示例显示split了vector的用法:
考虑以下字母向量:
testdata <- c("e", "o", "r", "g", "a", "y", "w", "q", "i", "s", "b", "v", "x", "h", "u")
目的是将这些字母分为voyels和consonants,即将其相应地拆分为字母类型。
首先创建一个分组向量:
vowels <- c('a','e','i','o','u','y') letter_type <- ifelse(testdata %in% vowels, "vowels", "consonants")
请注意,letter_type其长度与我们的vector相同testdata。现在我们可以split将测试数据分为两组,vowels并且consonants:
split(testdata, letter_type) #$consonants #[1] "r" "g" "w" "q" "s" "b" "v" "x" "h" #$vowels #[1] "e" "o" "a" "y" "i" "u"
因此,结果是一个列表,其中的名称来自我们的分组向量/ factor letter_type。
split 还有一种处理data.frames的方法。
考虑实例iris数据:
data(iris)
通过使用split,可以创建一个列表,其中data.frame每个虹膜种类(变量:种类)包含一个:
> liris <- split(iris, iris$Species) > names(liris) [1] "setosa" "versicolor" "virginica" > head(liris$setosa) Sepal.LengthSepal.WidthPetal.LengthPetal.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
(仅包含setosa组的数据)。
一种示例操作将是为每个虹膜种类计算相关矩阵。然后将使用lapply:
> (lcor <- lapply(liris, FUN=function(df) cor(df[,1:4]))) $setosa Sepal.LengthSepal.WidthPetal.LengthPetal.Width Sepal.Length 1.0000000 0.7425467 0.2671758 0.2780984 Sepal.Width 0.7425467 1.0000000 0.1777000 0.2327520 Petal.Length 0.2671758 0.1777000 1.0000000 0.3316300 Petal.Width 0.2780984 0.2327520 0.3316300 1.0000000 $versicolor Sepal.LengthSepal.WidthPetal.LengthPetal.Width Sepal.Length 1.0000000 0.5259107 0.7540490 0.5464611 Sepal.Width 0.5259107 1.0000000 0.5605221 0.6639987 Petal.Length 0.7540490 0.5605221 1.0000000 0.7866681 Petal.Width 0.5464611 0.6639987 0.7866681 1.0000000 $virginica Sepal.LengthSepal.WidthPetal.LengthPetal.Width Sepal.Length 1.0000000 0.4572278 0.8642247 0.2811077 Sepal.Width 0.4572278 1.0000000 0.4010446 0.5377280 Petal.Length 0.8642247 0.4010446 1.0000000 0.3221082 Petal.Width 0.2811077 0.5377280 0.3221082 1.0000000
然后,我们可以按组检索最佳的一对相关变量:(对关联矩阵进行整形/融合,对角线被滤除并执行选择最佳记录的操作)
> library(reshape) > (topcor <- lapply(lcor, FUN=function(cormat){ correlations <- melt(cormat,variable_name="correlatio); filtered <- correlations[correlations$X1 != correlations$X2,]; filtered[which.max(filtered$correlation),] })) $setosa X1 X2 correlation 2Sepal.WidthSepal.Length 0.7425467 $versicolor X1 X2 correlation 12Petal.WidthPetal.Length 0.7866681 $virginica X1 X2 correlation 3Petal.LengthSepal.Length 0.8642247
请注意,一种计算是在这种分组级别上执行的,可能有兴趣对结果进行堆叠,可以使用以下方法完成:
> (result <- do.call("rbind", topcor)) X1 X2 correlation setosa Sepal.WidthSepal.Length 0.7425467 versicolor Petal.WidthPetal.Length 0.7866681 virginica Petal.LengthSepal.Length 0.8642247