考慮由Seretosa,Versicolor和Virginica組成的虹膜數據集。對於4個變量有50個觀察值:萼片長度,萼片寬度,花瓣長度和花瓣寬度。如何使用R計算每個組的樣本協方差矩陣?在R中生成樣本協方差矩陣
-1
A
回答
0
下面是使用lapply
和dplyr
管的溶液:
data(iris)
library(dplyr)
l = lapply(unique(iris$Species), function(s) {
my.matrix = iris %>% filter(Species == s) %>% select(-Species) %>% as.matrix
return(cov(my.matrix))
})
結果l
是協方差矩陣的列表,在該物種的相同的順序,因爲它們出現在虹膜數據集。
1
可以在基礎R這樣做是爲了獲得協方差矩陣的每個組的命名列表:
tapply(seq_along(iris[[5]]), iris[[5]], FUN = function(ind) cov(iris[ind, -5]))
3
這裏是另一種方式......
lapply(split(iris[,-5],iris$Species),cov)
$setosa
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 0.12424898 0.099216327 0.016355102 0.010330612
Sepal.Width 0.09921633 0.143689796 0.011697959 0.009297959
Petal.Length 0.01635510 0.011697959 0.030159184 0.006069388
Petal.Width 0.01033061 0.009297959 0.006069388 0.011106122
$versicolor
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 0.26643265 0.08518367 0.18289796 0.05577959
Sepal.Width 0.08518367 0.09846939 0.08265306 0.04120408
Petal.Length 0.18289796 0.08265306 0.22081633 0.07310204
Petal.Width 0.05577959 0.04120408 0.07310204 0.03910612
$virginica
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 0.40434286 0.09376327 0.30328980 0.04909388
Sepal.Width 0.09376327 0.10400408 0.07137959 0.04762857
Petal.Length 0.30328980 0.07137959 0.30458776 0.04882449
Petal.Width 0.04909388 0.04762857 0.04882449 0.07543265
相關問題
- 1. 協方差矩陣lm對象R
- 2. 如何在Python中生成隨機協方差矩陣?
- 3. 更快的方法來生成協方差矩陣
- 4. Numpy協方差矩陣numpy.cov
- 5. 協方差矩陣gsl
- 6. 協方差矩陣計算
- 7. 提取R中估計協方差參數的協方差矩陣?
- 8. 按組的方差協方差矩陣
- 9. Proc GLM的方差協方差矩陣
- 10. PyMC - 方差 - 協方差矩陣估計
- 11. 在Matlab中計算協方差矩陣
- 12. 如何在data.table中按類別查找協方差矩陣R
- 13. 如何生成一個矩陣M,其協方差爲標識矩陣
- 14. OpenCV只用一個樣本計算協方差矩陣
- 15. 使用numpy和生成器計算協方差矩陣
- 16. Java中的計算協方差矩陣
- 17. 如何比較R中的兩個協方差矩陣?
- 18. 如何從R中的方差協方差矩陣得到迴歸係數?
- 19. 在R中創建樣本矩陣
- 20. 在R中生成邏輯矩陣
- 21. 從隨機矩陣生成樣本
- 22. R:矩陣誤差
- 23. 使用Excel計算協方差矩陣
- 24. 協方差矩陣與opencl和opencv
- 25. 顯示數據爲協方差矩陣
- 26. 兩個不同的協方差矩陣?
- 27. 協方差爲矩陣元素 - Matlab的
- 28. 橢圓的協方差矩陣
- 29. 使用VBA計算協方差矩陣
- 30. 替換協方差矩陣(pmvnorm)