2017-09-21 1 views
-1

Seretosa, Versicolor 및 Virginica 그룹으로 구성된 홍채 데이터 세트를 고려하십시오. Sepal Length, Sepal Width, Petal Length, Petal Width와 같은 4 가지 변수에 대한 50 가지 관찰이 있습니다. R을 사용하여 각 그룹에 대한 샘플 공분산 행렬을 어떻게 계산합니까? 그들이 설정 홍채 데이터에 나타나는샘플 공분산 행렬 생성 R

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 공분산 행렬의 목록 종의 순서대로이다 :

답변

0

여기 lapplydplyr 파이프를 이용한 용액이다.

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